In my app i'm iterating through URLs of images, decoding and putting them in an ArrayList<Bitmap>
.
They may vary greatly in size, so i'm doing a "pre-decode" with the inJustDecodeBounds = true
option to calculate the necessary inSampleSize
value for the actual decode.
See my method for this below, i hope it's not too hard to understand. Basically i'm aiming for a size similar to the screen size 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 for calculating screenPixels
:
Display display = getWindowManager().getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
int screenPixels = screenSize.x * screenSize.y;
I'm going through ~60 images and around 40 my app crashes with java.lang.OutOfMemoryError
.
As i understand, with inJustDecodeBounds = true
there's no memory allocated, and if my method is correct (i believe it is), very big images get very big inSampleSize
s, so i don't know what could be the problem.
Would appreciate any advice.