我要求在我的应用程序中显示许多图像。这些是jpgs和pngs,我将它们加载到ImageViews中,如下所示:
tile.setImageResource(R.drawable.tile_highlight);
我目前遇到OutOfMemory问题(java.lang.OutOfMemoryError: bitmap size exceeds VM budget
)
我搜索并发现了其他一些帖子,他们都建议您手动回收ImageView的位图,如下所示:((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle();
将从内存中转储它。
但在我的情况下,由于我没有使用setBitmap()
将图像加载到ImageView对象上,当我尝试运行上面的代码时,它返回NullPointerException
,更准确地说,是方法getBitmap()
返回null,没有位图?!?!
我是否需要返回我的代码并更改我在ImageViews中加载所有图像的方式,然后尝试使用recycle()
方法?或者我如何释放内存以使其不再崩溃?
修改
我尝试过这样的事情:imageView.setImageResource(-1);
希望它会从内存中删除图像并用...... null或其他东西替换它,但它似乎无助于原因。
答案 0 :(得分:4)
如果您可以发布一些代码,将会很有帮助。具体来说,您是如何设置ImageView
个对象的图像的。如果您没有使用位图,我希望getBitmap()
将返回null。但是,如果您使用其他类型Drawable
或以其他方式设置图像,则可能会采用类似的路线,但不涉及位图。
编辑:
好的,试一试。您可以从以下资源创建Bitmap
:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
然后,使用这样的位图,考虑到img是你的ImageView
:
img.setImageBitmap(bm);
//Do some stuff with it, then when memory gets low:
((BitmapDrawable)img.getDrawable()).getBitmap().recycle();
当然,这是考虑到你正在参加一项活动。如果没有,您必须处理上下文并将getResources()
替换为context.getResources()
。
答案 1 :(得分:2)
如果要将图像从drawable设置为ImageView,请不要将ImageView.setImageResource(int resId)
直接用于drawable id。而是获得按比例缩小的位图(如果适用)并将其设置为imageView。像这样:
这适合我。
iv.setImageBitmap(decodeResource(getResources(), R.drawable.big_image));
private static Bitmap decodeResource(Resources res, int id) {
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
for (options.inSampleSize = 1; options.inSampleSize <= 32; options.inSampleSize++) {
try {
bitmap = BitmapFactory.decodeResource(res, id, options);
Log.d(TAG_LOG, "Decoded successfully for sampleSize " + options.inSampleSize);
break;
} catch (OutOfMemoryError outOfMemoryError) {
// If an OutOfMemoryError occurred, we continue with for loop and next inSampleSize value
Log.e(TAG_LOG, "outOfMemoryError while reading file for sampleSize " + options.inSampleSize
+ " retrying with higher value");
}
}
return bitmap;
}
答案 2 :(得分:1)
尝试
((BitmapDrawable)im.getBackground()).getBitmap().recycle();
答案 3 :(得分:1)
我认为您应该以较低的分辨率显示图像。这将解决OOM问题。您还可以阅读Android开发人员指南link
答案 4 :(得分:1)
OutOfMemory错误出现在你使用位图时可能没有释放位图(可能是大尺寸),所以为了防止这种情况,我们应该记住重新调整大小,采取弱引用等。 但是有很好的图书馆可以照顾所有问题,其中一个是毕加索。请看看 -