I’m curious if the following code will leak…
data = getBitmapdataFromCameraCallback();//this is immutable, so...
//make a mutable copy...
originalUserPhoto = BitmapFactory.decodeByteArray(data, 0, data.length).copy(Config.ARGB_8888, true);
Matrix matrix = new Matrix();
// -1 doesn't reverse it for some oddball reason, so, we get REALLY close to -1
matrix.preScale(-0.999f, 1.0f);//don't ask don't tell
originalUserPhoto = Bitmap.createBitmap(originalUserPhoto, 0, 0,
originalUserPhoto.getWidth(), originalUserPhoto.getHeight(),
matrix, true);
If I’m modifying the originalUserPhoto in place (notice I’m passing it in as the source of createBitmap), does that leak the original data? Or is the JVM smart enough to release the data that was there?
Yes and no. You have two Bitmap objects (the first one created by decodeByteArray, the second one by createBitmap), and the first one has nothing referencing it, so during a future garbage collection cycle, it is likely to get deleted.
That said, while the native backing store for the bitmap will be deleted too when the Bitmap is recycled, I would recommend manually deleting the first bitmap after you’re done using it – keep it in a separate reference and call
recycle()on it. Bitmaps can be very expensive.Btw, if the point of your createBitmap is just to scale, I would consider scaling the original bitmap down as you decode it by passing in options. You won’t be able to scale to exactly that size you want, but at least you won’t end up with an unwieldly huge bitmap that you’ll scale down to a tenth of its size. That will be faster and avoid a memory spike.