【发布时间】:2015-05-12 13:25:32
【问题描述】:
在我的应用程序中,我正在遍历图像的 URL,解码并将它们放入 ArrayList<Bitmap>。
它们的大小可能相差很大,所以我正在使用inJustDecodeBounds = true 选项进行“预解码”,以计算实际解码所需的inSampleSize 值。
请看下面我的方法,我希望它不会太难理解。基本上我的目标是与设备的屏幕尺寸相似。
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);
}
}
计算screenPixels的代码:
Display display = getWindowManager().getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
int screenPixels = screenSize.x * screenSize.y;
我浏览了大约 60 张图片,其中大约 40 张我的应用因java.lang.OutOfMemoryError 而崩溃。
据我了解,inJustDecodeBounds = true 没有分配内存,如果我的方法是正确的(我相信它是正确的),那么非常大的图像会变得非常大 inSampleSizes,所以我不知道可能是什么问题。
不胜感激。
【问题讨论】: