Bitmap的高效加载

BitmapFactory类提供了四类方法:decodeFile,decodeResource,decodeStream,decodeByteArray,分别用于支持从文件系统、资源、输入流和字节数组中加载出一个Bitmap对象。如何高效加载一个Bitmap?其核心思想就是采用BitmapFactory.Options来加载所需尺寸的图片,主要是用到它的inSampleSize参数,即采样率。通过这个参数可以按照一定的比例对图片进行缩放,这样就会降低内存占用从而在一定程度上避免OOM,提高加载Bitmap的性能。
对于如何获取采样率呢?可以采用如下流程:
1、将BitmapFactory.Options的inJustDecodeBounds参数设置为true并加载图片;
2、从BitmapFactory.Options中取出图片的原始宽高信息,他们对应outWidth和outHeight参数;
3、根据采样率的规则并结合目标View所需的大小计算出采样率inSampleSize;
4、将BitmapFactory.Options的inJustDecodeBounds参数设为false,然后重新加载图片。
经过上述4个步骤,加载出的图片就是缩放后的图片。当inJustDecodeBounds设为true时,BitmapFactory只会解析图片的原始宽高,并不会真正的加载图片。
将上述4个步骤用程序来实现:

   public static Bitmap decodeSampleBitmapFromResource(Resources res,
                                                        int resId,
                                                        int reqWidth,
                                                        int reqHeight){
        BitmapFactory.Options options = new BitmapFactory.Options();
        //1
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res,resId,options);
        //2\3
        options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
        //4
        options.inJustDecodeBounds = false;
        
        return BitmapFactory.decodeResource(res,resId,options);
                
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    
        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 1;
        
        if (width > reqWidth || height > reqHeight){
            int halfWidth = width / 2;
            int halfHeight = height / 2;
            
            while ((halfWidth / inSampleSize) >= reqWidth && (halfHeight / inSampleSize) >= reqHeight){
                inSampleSize *= 2;
            }
         }
        return inSampleSize;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值