【问题标题】:Bitmap out of memory位图内存不足
【发布时间】:2012-08-27 18:34:09
【问题描述】:

我正在尝试从图库中获取图片(按意图)。
我收到了这个错误:

985120-byte external allocation too large for this process.
Out of memory: Heap Size=4871KB, Allocated=2472KB, Bitmap Size=19677KB
VM won't let us allocate 985120 bytes

这是我获取图像的代码:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   ....
   mBitmap = Media.getBitmap(this.getContentResolver(), data.getData());
   ...
}

我该如何解决?

-------- 更新 ---------

我注意到,如果我选择预先存在的图像(已安装 HTC 照片),我会收到此错误。如果我选择从相机中挑选的图像,一切正常。

所以,我根据这个http://developer.android.com/training/displaying-bitmaps/load-bitmap.html更改我的代码:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;

InputStream stream = getContentResolver().openInputStream(data.getData());
mBitmap = BitmapFactory.decodeStream(stream,null,options);
stream.close();

但是现在位图是 NULL !!!

【问题讨论】:

标签: android bitmap out-of-memory


【解决方案1】:

看起来您的应用程序使用了很多高分辨率位图(位图内存分区为 19677KB)。 'heap' 和 'allocated' 的 sie 很正常,应该没有问题。确保从内存中删除未使用的位图。您可以通过调用bitmap.recycle() 或将其引用设置为空来从内存中释放位图。如果您出于性能原因想要缓存位图,请查看LruCache

【讨论】:

  • LruCache 更多细节示例
  • 当我在我的画廊(安装了 htc 图像)中选择 19MB(可能)的示例图像时出现此错误。
  • 好吧,我以为报错信息中提到的985120字节是你图片的大小。 19MB 是很多数据,如果您使用的是低规格的 HTC 手机,可能没有任何好的解决方案。有一个功能可以在解析时动态调整图像大小,等等……
  • 如果我在第二次使用之前添加 stream.close() ,这项工作。否则我得到 bitmap=null
【解决方案2】:

我总是在 while 循环中包装解码,增加 inSampleSize 并捕获 OutOfMemoryError。这将为您提供最大可能的分辨率图像。始终使用 LRU 缓存!

    Bitmap image;
    boolean success = false;int counter = 0;
    while (success == false && counter < 10)
    {
        try
        {
            image = BitmapFactory.decodeFile(photoPath, options);
            success = true;
        }
        catch(OutOfMemoryError e)
        {
            System.gc();
            options.inSampleSize++;
            counter++;
        }
    }

【讨论】:

    猜你喜欢
    • 2011-10-04
    • 2013-05-08
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    相关资源
    最近更新 更多