ImageView OutofMemoryException

做~自己de王妃 提交于 2019-11-28 10:36:06

The max size of a bitmap is 2048x2048, if your bitmap is bigger than this you should scale it..
I'm using this method to scale a bitmap:

public static Bitmap scaleBitmap(Bitmap bitmapToScale, float newWidth, float newHeight) {   
    if(bitmapToScale == null)
        return null;
    //get the original width and height
    int width = bitmapToScale.getWidth();
    int height = bitmapToScale.getHeight();
    // create a matrix for the manipulation
    Matrix matrix = new Matrix();

    // resize the bit map
    matrix.postScale(newWidth / width, newHeight / height);

    // recreate the new Bitmap and set it back
    return Bitmap.createBitmap(bitmapToScale, 0, 0, bitmapToScale.getWidth(), bitmapToScale.getHeight(), matrix, true);
} 

You can also check the memory state using this:

ActivityManager actMgr = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo minfo = new ActivityManager.MemoryInfo();
actMgr.getMemoryInfo(minfo);
if(minfo.lowMemory) { //do something}

You can also load the image dimension without loading the complete image.

android.graphics.BitmapFactory.Options options = new
    android.graphics.BitmapFactory.Options();

options.inJustDecodeBounds = true;

android.graphics.BitmapFactory.decodeFile(filepath, options);

Now you have the image dimension available via:

options.outHeight
options.outWidth

Try to read the official Android Developer docs:Loading Large Bitmaps Efficiently in this link,Given that you are working with limited memory (mobile phones), ideally you only have to load a lower resolution version in memory. Follow the advices posted in the link and you will avoid your OM problem

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