0

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

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 !!!

4

2 回答 2

1

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

于 2012-08-27T18:41:05.710 回答
0

我总是在一个 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++;
        }
    }
于 2012-08-27T19:44:48.457 回答