0

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();
view.getLocalVisibleRect(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?

Community
  • 1
  • 1
teddy
  • 2,158
  • 4
  • 26
  • 34
  • Calculate the proper `inSampleSize`. Right now, your `BitmapFactory` code will load in the entire image at full resolution. As you note, you do not need this. `inSampleSize` on the `BitmapFactory.Options` tells `BitmapFactory` to give you a scaled bitmap back, one that is closer to the desired size. – CommonsWare Oct 27 '16 at 19:17
  • @CommonsWare this works. Now dynamically loading the image consumes only 1.1MB additional memory as expected! If you post it as an answer, I will up vote it. – teddy Oct 27 '16 at 19:51

2 Answers2

1

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

I have experienced this too but with much smaller images. I found out of that this was happening because I was using the same image size for all screen resolutions. I recommend you have different sizes of the same image and put them in the appropriate folders.