【发布时间】:2014-06-22 20:10:50
【问题描述】:
我正在处理多达 1200 张图像。在此处找到的先前问题的帮助下,我将其优化为从 100 个图像到 500 个图像。现在,这就是我所拥有的:
public Bitmap getBitmap(String filepath) {
boolean done = false;
int downsampleBy = 2;
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, options);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
options.inPreferredConfig = Config.RGB_565;
while (!done) {
options.inSampleSize = downsampleBy++;
try {
bitmap = BitmapFactory.decodeFile(filepath, options);
done = true;
} catch (OutOfMemoryError e) {
// Ignore. Try again.
}
}
return bitmap;
}
这个函数在循环中被调用,它运行得非常快,直到它到达第 500 张图像。此时它会变慢,直到它最终在第 600 张图像左右停止工作。
此时我不知道如何对其进行优化以使其正常工作。您认为发生了什么,我该如何解决?
编辑
// Decode BItmap considering memory limitations
public Bitmap getBitmap(String filepath) {
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, options);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
options.inPreferredConfig = Config.RGB_565;
options.inDither = true;
options.inSampleSize= calculateInSampleSize(options, 160, 120);
return bitmap = BitmapFactory.decodeFile(filepath, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
对已接受的答案进行了更改。使用 Google 教程中的函数来获得正确的样本量。在清单中添加了 largeHeap,并且在循环所有图像之前只调用一次 System.gc()。
【问题讨论】:
-
我不知道这是不是一个糟糕的计划,但是您是否尝试过调用 System.gc() 来防止内存耗尽?
-
@Zhuinden 我没有,我应该在哪里调用这个?
标签: android bitmapfactory