Android: Out of Memory Exception / How does decodeResource add to the VM Budget?

天涯浪子 提交于 2019-12-04 07:25:56
  • When you decode the Bitmap from an image resource like png, it depends more on the dimensions of image rather then the size in KBs.
  • Try if you can reduce the dimensions of original image without really impacting your output.
  • Try reusing the bitmaps rather then keep decoding them.
  • Explore more options with BitmapFactory.Options() object, for example increasing inSampleSize can reduce the amount of memory required by the image. e.g
    BitmapFactory.Options o=new BitmapFactory.Options();
    o.inSampleSize = 4;
    o.inDither=false;                     //Disable Dithering mode
    o.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
    myBitMap=BitmapFactory.decodeResource(getResources(),ID, o);
    
  • One useful tricky solution if no other optimizations are really working out for you is that, you can catch the OutOfMemoryException and then can reduce the quality to max.. i.e. setting the inSampleSize to 16. It will reduce the quality of your images but at least will save your application from crashing, i did this in one of my app where I needed to load huge MP image in a bitmap.

My snippet to get image from resources safety. You can set your own sampleSize as threshold of image quality (larger sampleSize is lower image quality).

public static Bitmap loadBitmapSafety(int resDrId,  Context context){
    return loadBitmapSafety(resDrId, 1, context);
}

private static Bitmap loadBitmapSafety(int resDrId, int sampleSize, Context context){
    BitmapFactory.Options ops = new BitmapFactory.Options();
    ops.inSampleSize = sampleSize;

    try {
        return BitmapFactory.decodeResource(context.getResources(), resDrId, ops);

    } catch (OutOfMemoryError e) {
        if (sampleSize == 4)
            return null;
        return loadBitmapSafety(resDrId, sampleSize +1, context);

    } catch (Exception e){
        return null;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!