zeme
zeme

Reputation: 437

Java memory allocation workaround

I'm trying to write a program for the Android platform where I deal with images a lot. Consider the following:

Bitmap b = BitmapFactory.decodeFile(File imagePath) // 5mb picture is stored into memory as with 32bits of memory per pixel --> almost run out of memory

I will want to change the pixels in this Bitmap, but for some reason the Bitmap returned is immutable. I figured that making a copy of it using b.copy(Config config, boolean isMutable) would do the trick, although I run into a RuntimeExeception saying that the VM won't let us allocate blah blah bytes of memory. My question is, would the following line

Bitmap mutable = BitmapFactory.decodeFile(File imagePath).copy(config, true);

allocate less memory and therefore be safely used to get my mutable copy of the Bitmap, given that there is no reference to the original immutable Bitmap? This seems to do the job sometimes, but I would like an explanation of whether I'm just talking nonsense or if what I'm doing is a clever workaround to achieve my task.

Upvotes: 1

Views: 335

Answers (2)

dmon
dmon

Reputation: 30168

The second case might work because it happens to clear the reference to the first bitmap quickly enough, though it doesn't seem like it should work, since both references are alive at the same time still. However, 5mb picture seems like it's pushing it (what resolution is it?). Be aware that the memory available to an application varies wildly (mostly dependent on the screen resolution of a particular device) so whatever you're doing probably won't work in another lesser device. So the real question is: Do you really need the full-size bitmap?

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

No. The copy method has a reference to the immutable bitmap while copying it to the mutable one. This reference is called this. So you still have a reference to both bitmaps at the same time.

The Options object that you can pass to the BitMapFactory decodeFile method has an inMutable option, though, which would avoid the immutable bitmap completely.

Upvotes: 2

Related Questions