AN Gridview加载图片缩略图出现OOM的问题解法

来源:互联网 发布:伟达公关 知乎 编辑:程序博客网 时间:2024/05/21 16:54

出现这个OOM是缺乏了常识,所以在这里补全

出现OOM的原因是:把图片全部加载到内存当中再进行缩放

出现OOM的关键代码:BitmapFactory.decodeFile(file.getAbsolutePath());

解决的关键是:获取到图片的宽高等关键属性加载入内存而不是原始图片,然后再进行缩放

解决OOM的关键代码:BitmapFactory.decodeFile(filePath, options) ;

先来看例子

    public static int calculateRatioSize(BitmapFactory.Options options,            int reqWidth, int reqHeight) {        final int height = options.outHeight;        final int width = options.outWidth;        int inSampleSize = 1;        if (height > reqHeight || width > reqWidth) {            final int heightRatio = Math.round((float) height / (float) reqHeight);            final int widthRatio = Math.round((float) width / (float) reqWidth);            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;        }        return inSampleSize;    }    public static Bitmap decodeSampledBitmapFromFilePath(String filePath,            int reqWidth, int reqHeight) {        final BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;// A        BitmapFactory.decodeFile(filePath, options) ;        options.inSampleSize = calculateRatioSize(options, reqWidth, reqHeight);        options.inJustDecodeBounds = false;        return BitmapFactory.decodeFile(filePath, options) ;// B    }
BitmapFactory.Options options的inJustDecodeBounds设置为true

则可以使得不加载原始图片进入内存,设置之后A返回的Bitmap是为null的

然后根据给定的需要缩放的宽高来进行计算缩放比例inSampleSize,

最后把options.inJustDecodeBounds=false关掉,重新读入bitmap对象,这是B 就是所要的图片缩略图


最后附上参考的两个博客:

点击打开链接1

点击打开链接2


0 0
原创粉丝点击