在实际的项目开发过程中,因为手机内存有限,加载图片过程中经常会发生oom的问题,因此,如何避免oom成了android开发过程中必不可少的一个环节。需要使用到BitmapFactory中的一个强大的工具:
BitmapFactory.Options
通过计算采样率等比例压缩bitmap图片的宽高。从而达到避免oom的情况。刚提到采样率:
inSampleSize
这又是一个神奇的东西,通过采样率可以设置图片缩放的比例,默认值为1。当采样率为2事,图片的宽高为原来的1/2,像素比为原来的1/4。例如一张图片大小的4m,设置采样率为2的话图片大小将会缩小到1m,宽高也是等比缩小一半。
inJustDecodeBounds
这个关键参数是一个boolean类型,为true的时候的意思是代表加载图片不会计入内存,只是用于计算图片的宽高,设置成false才是实际加载图片。
因此实际的代码操作就是:
public class BitmapOptionActivity extends AppCompatActivity {
private ImageView icon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bitmap_option);
icon = (ImageView) findViewById(R.id.icon);
Bitmap bitmap = bitmapOption(getResources(), R.mipmap.danfan, 50, 50);
icon.setImageBitmap(bitmap);
}
/**
* 压缩指定尺寸图片
* @param res
* @param resId
* @param reqWidth
* @param reqheight
* @return
*/
private Bitmap bitmapOption(Resources res , int resId, int reqWidth, int reqheight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeResource(res,resId,options);
int height = options.outHeight;
int width = options.outWidth;
//指定采样率
int inSampleSize=1;
if(height>reqheight||width>reqWidth){
int halfWidth = width/2;
int halfHeight = height/2;
//采样率以2的指数幂增长
while((halfWidth/inSampleSize)>=reqWidth&&(halfHeight/inSampleSize)>=reqheight){
inSampleSize*=2;
}
}
//设置采样率
options.inSampleSize=inSampleSize;
options.inJustDecodeBounds=false;
return BitmapFactory.decodeResource(res,resId,options);
}
}
主要是采样率的计算里面有一些技巧,判断如果实际大小大于需要设置的大小,就将实际大小除2,在进行比较,直到实际大小满足条件,然后设置采样率。