[Also asked on
StackOverflow<http://stackoverflow.com/questions/11849443/cropping-a-bitmap-causes-undefined-behavior>
]
I am facing some really strange issues manipulating bitmaps on the Android
platform. Basically, I'm capturing the surface of a view as a Bitmap:
this.setDrawingCacheEnabled(true);
Bitmap drawing = Bitmap.createBitmap(this.getDrawingCache());
this.setDrawingCacheEnabled(false);
Since the view contains a black & white line drawing, I want to remove the
white margins, so I compute the bounding box coordinates of the drawing:
int top = drawing.getHeight();
int left = drawing.getWidth();
int right = 0;
int bottom = 0;
for (int i = 0; i < drawing.getWidth(); ++i) {
for (int j = 0; j < drawing.getHeight(); ++j) {
int pixel = drawing.getPixel(i, j);
if (pixel == getResources().getColor(R.color.stroke_color)) {
if (top > i) top = i;
if (left > j) left = j;
if (bottom < i) bottom = i;
if (right < j) right = j;
}
}
}
(yeah, it's kinda' slow and I need to figure out how to lock the Bitmap in
memory with copyPixelsToBuffer before KI execute this loop, but right now I
just want it to work properly)
If I save drawing to a file it looks fine and it has the expected
dimensions. If I log the top, left, bottom and right variables, they seem
to contain the right values.
But once I do this:
drawing = Bitmap.createBitmap(drawing, left, top, right - left, bottom - top);
all hell breaks loose. Depending on the drawing, sometimes I get unexpected
cropping, other times I get some exception that the width or height of
drawing are too small compared to the rest of the parameters, other times I
get some bizarre out of bounds exception, that the code in createBitmaptried to
access some very large index (close to (65536, 65536)) and other
times I get a nasty crash and the application just dies.
I guess the problem is caused by some memory corruption and it must be a
problem with the way I'm manipulating the Bitmap object, because I get the
same behavior in the emulator as well as on my HTC One X phone.
Things that I've discovered:
- createBitmap produces an unmutable image, but I see no reason I would
need it to be mutable. As a test, I tried to make it mutable with
Bitmap.clone(), but it didn't change anything.
- I expect createBitmap to just assign the result to drawing and I see no
reason to create a temporary object (I tried, but it does not help).
At this point, any suggestions are welcome.
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en