Android开发之Bitmap的高效加载

时间:2022-09-03 21:25:26

BitmapFactory类提供了四类方法:decodeFile, decodeResource, decodeStream和decodeByteArray

分别用于支持从文件系统,资源,输入流以及字节数组中加载出一个Bitmap对象,前两者又间接调用了decodeStream

为了避免OOM,可以通过采样率有效的加载图片

如果获取采样率?

1.将BitmapFactory.Options的inJustDecodeBounds的参数设置为true并加载图片

2.从BitmapFactory.Options中取出图片的原始宽高,它们对应outWidth和outHeight参数

3.根据采样率的规则并结合目标View的所需大小计算采样率inSampleSize

4.将BitmapFactory.Options的inJustDecodeBounds的参数设置为false,并重新加载图片

上述步骤通过代码体现:

public static Bitmap decodeSampledBitmapFromResource(Resource 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 static int calculateInSampleSize(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 halfHeight = height / 2;
        final int halfWidth = width / 2;

        while((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth){
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}