Hacking Bear Hacking Bear - 11 months ago 66
Android Question

Android still uses excessive memory when loading background image

I have read multiple posts like this about memory usage of background image.

  1. my background image is 2048x1365 59KB JPEG; its uncompressed bitmap is 11MB

  2. the background on the view for the particular device would be 480x605, so usage would be 1.1MB (480x605x4)

  3. my app originally uses 12MB without background image

  4. placing the image in drawable-nodpi/ and set it in the layout XML cause the memory usage to 23MB; so exactly base + BMP size

  5. Using BitmapFactory to decode the image (moved to raw/) according to the advice results in 33MB of memory usage. (See codes below.)

Codes to set the background

View view = findViewById(R.id.main_content);
Rect rect = new Rect();
BitmapFactory.Options options = new BitmapFactory.Options();
options.outHeight = rect.height();
options.outWidth = rect.width();
options.inScaled = false;
Bitmap backgroundBitmap = BitmapFactory.decodeResource(getResources(), backgroundId, options);
view.setBackgroundDrawable(new BitmapDrawable(getResources(), backgroundBitmap));

What goes wrong? What else can I do to shrink the memory usage?

Answer Source

The trick to getting BitmapFactory to give you a low-memory image is to fill in inSampleSize on the BitmapFactory.Options. This tells BitmapFactory to downsample the image as it loads, giving you a lower-resolution image, but one that is better tuned to whatever use you plan to put it to. You would need to calculate the desired inSampleSize that you want, based on the resolution of the ImageView (or whatever) that you are using the image for.

This sample app demonstrates loading some images out of assets/ with different inSampleSize values.