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

出现这个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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值