图片的高效加载

前言

最近写了一个相册应用,发现自己的界面卡的要死,有时候还会崩掉,后来发现是自己加载图片的时候没有处理,导致OOM了,下面就记录一下图片加载和缩放。

Bitmap构建

在Android程序中,无论图片是jpg 还是png, 都是表示为一个Bitmap对象, 我们一般是通过BitmapFactory来构建,它主要有四种常用方法

BitmapFactory.decodeFile(...)
BitmapFactory.decodeResource(...)
BitmapFactory.decodeStream(...)
BitmapFactory.decodeByteArray(...)

加载图片时采用BitmapFactory.Options来对图片进行缩放,主要思想是通过改变图片的采样率,对应inSampleSize参数,当采样率为1 的时候图片为原始大小,采样率为2 的时候宽高变为原来的1/2,大小为原来的1/4。 官方文档中指出,采样率的值必须是2的指数,即1,2,4,8… ,当我们传递的采样率不是2的指数时会被自动向下取整选择一个最接近的2的指数。

    private Bitmap decodeBitmap(int resId, int width,int height){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(mContext.getResources(),resId,options);
        options.inSampleSize = calculateInSampleSize(options,width,height);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(mContext.getResources(),resId,options);
    }

    public 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){
            inSampleSize *= 2;
            int hHeight = height / inSampleSize;
            int hWidth  = width / inSampleSize;
            while (hHeight >= reqHeight && hWidth >= reqWidth){
                hHeight = height / inSampleSize;
                hWidth  = width / inSampleSize;
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

上面代码中inJustDecodeBounds表示不加载图片,只会解析原始图片的宽高。

你可能感兴趣的:(Android,android)