高效加载Bitmap

高效加载Bitmap:

为了防止加载bitmap出现oom的情况,我们一般需要缩小一个bitmap的大小。缩小内存大小有个办法,首先你可以降低图片的采样率。在BitmapFactory.Options里面可以设置参数imSampleSize的值(采样率)。当imSampleSize = 1,表示原图;当imSampleSize = 2,表示宽高都缩小2倍,整体像素为原来的1/4。

现在结合一个实际情况来讲:比如ImageView的大小是100 * 100。而图片原始大小为200 * 200,那么采样率inSampleSize设为2最合适,那代码怎么写呢?

  1. 讲BitmapFactory.Options的inJustDecodeBounds参数设置为true。并加载图片。
  2. 讲BitmapFactory.Options中取出图片的原始宽高,他们对应的是outwidth和outHeight.
  3. 根据采样率的规则结合目标View的所需大小计算出采样率inSampleSize
  4. 将BitmapFactory.Options的inJustDecodeBounds参数设置为fasle,然后重新加载图片。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static Bitmap decodeSampleBitMapFromResource(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.decodeResources(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)>=reqHieght && (halfWidth/inSampleSize)>=reqWidth){
inSampleSize *=2;
}
}
return inSampleSize;
}

有了上面这个方法就很简单了,比图ImageView所期望的图片大小为100*100,那么我们就可以高效的加载了:

1
mImageView.setImageBitmap(decodeSampleBitmapFromResource(getResource(),R.id.bg,100,100));