Java – What’s wrong with this bitmap’s inSampleSize calculation method? Out of memory

What’s wrong with this bitmap’s inSampleSize calculation method? Out of memory… here is a solution to the problem.

What’s wrong with this bitmap’s inSampleSize calculation method? Out of memory

In my application, I iterate through the URLs of images, decode them, and put them into an ArrayList<Bitmap>

Their sizes can vary greatly, so I’m using the inJustDecodeBounds = true for the “pre-decode” option to calculate the value of the necessary inSampleSize to actually decode.

Check out my method below, I hope it’s not too hard to understand. Basically, my goal is to be similar in size to the screen of the device.

for (Element e: posts) {
    if (!e.id().equals("")) {
        preparing decode
        options = new BitmapFactory.Options();
        input = new URL(e.url).openStream();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(input, null, options);
        input.close();

setting inSampleSize if necessary
        int picPixels = options.outWidth * options.outHeight;
        int picScreenRatio = picPixels / screenPixels;
        if (picScreenRatio > 1) {
            int sampleSize = picScreenRatio % 2 == 0 ? picScreenRatio : picScreenRatio + 1;
            options.inSampleSize = sampleSize;
        }

actual decode
        input = new URL(e.url).openStream();
        options.inJustDecodeBounds = false;
        Bitmap pic = BitmapFactory.decodeStream(input, null, options);
        input.close();

picList.add(pic);
    }
}

Code to calculate screenPixels:

Display display = getWindowManager().getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
int screenPixels = screenSize.x * screenSize.y;

I’m looking at about 60 images, of which about 40 of my app crashes with java.lang.OutOfMemoryError

As I understand it,

no memory is allocated with inJustDecodeBounds = true, and if my approach is correct (I believe it is), very large images become very large inSampleSize s, so I don’t know what the problem might be.

Any suggestions would be appreciated.

Solution

Whether you use inSampleSize, you can’t easily fit 60 bitmaps as large as a screen in memory.

Assuming a Full HD screen you get about 1920*1080*60*4 bytes.

This is approximately 500 MB of data.
You need to change your bitmap loading logic somehow.

In this Answer: You can find out how much memory you can count. It varies depending on various devices.

But always try to make your app as memory efficient as possible.

Related Problems and Solutions