在解码位图时捕获OutOfMemoryError

bit*_*bit 23 android bitmap out-of-memory

即使您已经尝试了一些减少内存使用的方法,捕获OutOfMemoryError是一个好习惯吗?或者我们应该不抓住异常?哪一个更好的做法?

try {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;
    bitmap = BitmapFactory.decodeFile(file, options);
} catch (OutOfMemoryError e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Ron*_*nie 36

抓住它一次并给予decodeFile另一次机会是一种很好的做法.抓住它并调用System.gc()并再次尝试解码.呼叫后它很可能会起作用System.gc().

try {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;
    bitmap = BitmapFactory.decodeFile(file, options);
 } catch (OutOfMemoryError e) {
    e.printStackTrace();

    System.gc();

    try {
        bitmap = BitmapFactory.decodeFile(file);
    } catch (OutOfMemoryError e2) {
      e2.printStackTrace();
      // handle gracefully.
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 调用System.gc()可能不太好,[http://code.google.com/p/android/issues/detail?id=8488#c80](http://code.google.com/p/ android/issues/detail?id = 8488#c80),无论如何,谢谢 (2认同)

jsa*_*arb 9

我做了类似这样的事情:我只是为了尝试缩小图像直到它工作才捕获错误.最终它根本无法运作; 然后返回null; 否则,成功返回位图.

在外面我决定如何处理位图,无论它是否为空.

// Let w and h the width and height of the ImageView where we will place the Bitmap. Then:

// Get the dimensions of the original bitmap
BitmapFactory.Options bmOptions= new BitmapFactory.Options();
bmOptions.inJustDecodeBounds= true;
BitmapFactory.decodeFile(path, bmOptions);
int photoW= bmOptions.outWidth;
int photoH= bmOptions.outHeight;

// Determine how much to scale down the image. 
int scaleFactor= (int) Math.max(1.0, Math.min((double) photoW / (double)w, (double)photoH / (double)h));    //1, 2, 3, 4, 5, 6, ...
scaleFactor= (int) Math.pow(2.0, Math.floor(Math.log((double) scaleFactor) / Math.log(2.0)));               //1, 2, 4, 8, ...

// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds= false;
bmOptions.inSampleSize= scaleFactor;
bmOptions.inPurgeable= true;

do
{
    try
    {
        Log.d("tag", "scaleFactor: " + scaleFactor);
        scaleFactor*= 2;
        bitmap= BitmapFactory.decodeFile(path, bmOptions);
    }
    catch(OutOfMemoryError e)
    {
        bmOptions.inSampleSize= scaleFactor;
        Log.d("tag", "OutOfMemoryError: " + e.toString());
    }
}
while(bitmap == null && scaleFactor <= 256);

if(bitmap == null)
    return null;
Run Code Online (Sandbox Code Playgroud)

例如,对于3264x2448的图像,循环在我的手机上迭代2次,然后它可以工作.