Bitmap优化方案

        在Android中,我们可以通过Bitmap来将一张图片加载至ImageView,可以使用的API有decodeFile,decodeResource,decodeStream,decodeByteArray。

           高效的加载大图主要策略是避免图片尺寸超过控件所需的尺寸。我们可以通过设定BitmapFactory.Option中的inSampleSize来修改图片比例,如果将inSample设置为2,那么宽高缩小为原来的1/2,像素缩小为原来的1/4,那么对内存的需求也就缩小为原来的1/4,这样可以有效避免OOM。那么我们怎么通过修改inSampleSize来缩小图片呢?

                      1.将BitmapFactory.Options中的inJustDecodeBounds设置为true。

                      2.从BitmapFactory.Options取出图片属性。

                      3.根据获得的属性与控件属性进行对比采样,计算出合适的inSampleSize(系统规定为2的指数)。

                      4.将BitmapFactory.Options中的inJustDecodeBounds设置为false,重新加载图片。

            代码操作如下:

                       

public Bitmap decodeSampleBitmapFromResource(Resources res, int resId,int reqWidth,int reqHeight){
            final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res,resId,options);
        options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res,resId,options);
    }

         

public int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){
        if(reqWidth == 0 || reqHeight == 0){
            return 1;
        }
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if(height > reqHeight || width > reqWidth){
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth){
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

             

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值