bmjohns
bmjohns

Reputation: 6470

Setting large image in ImageView from res crashes App

I have a .png file I would like to use in my app. This image is rather huge, approximately 328x32765 pixels, 751KB in size and is in my res folder. I get an error message of "java.lang.OutOfMemoryError: bitmap size exceeds VM budget" from trying to set this image into my layout.

I am not sure if it is relevant, but I also have about 730 buttons on that same page, that load and work ok, but I am thinking that maybe those buttons are using a lot of memory as well?

Either way, is there a simple fix to help solve this issue or make my .png image use less memory?

Upvotes: 1

Views: 4785

Answers (3)

Nar Gar
Nar Gar

Reputation: 2591

Although your image is 731KB big, the actual inflated bitmap size will be almost 41 megabytes. You get the error because the device is unable to allocate 41MB at once.

Unfortunately, there is no other way to work this out except by loading a scaled down version of the image.

Use Bitmap.Options class and specify a scaled factor:

2 - means make each side twice smaller

3 - three times smaller,......

x - x times smaller

the good news is that the resulting inflated bitmap size will be 41/(x * x)MB:

2 - 41/4 = 10.25MB

3 - 41/9 = 4.5MB

4 - 41/16 = 2.6MB .....

try this out and test on multiple devices.

Alternatively, break down the image into considerably smaller images and use a ListView with no borders or dividers, such that you'll still see a smooth image but the ListView will also take care of initiating and discarding the pieces as they are needed. (Note that you'll loose the capability of horizontal scrolling because ListView scrolls vertically only - just in case this is a concern for you).

Upvotes: 0

Sreedev
Sreedev

Reputation: 6653

Android cant handle large bitmaps OOM error will occur.Its not an a=unexpected error this is a big problem faced by many developers.try Googling many docs you will find explianing about the OOM error.I had also struggled while developing an application.For Removing this, sampling big images is the only one way.

   int scale = "Image byte length" / 320000;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = scale / 2 + scale % 2* 2;
   decryptedimage=BitmapFactory.decodeByteArray(decryptedData,0,decryptedData.length,options);

Upvotes: 0

gorbos
gorbos

Reputation: 311

A bitmap takes a lot of memory as mentioned in the tutorial from the android's site itself regarding bitmaps

Displaying Bitmaps

EDIT:

Try using the function "Bitmap.createScaledBitmap(Bitmap, width, height, filter);" or try to use the "BitmapFactory.Options" class as mentioned in the tutorial.

"BitmapFactory.Options" class helps a lot since its function itself helps developers to minimize the use of VM in loading Bitmaps by caching the loaded bitmap.

Upvotes: 2

Related Questions