在Android中,我们可以通过Bitmap来将一张图片加载至ImageView,可以使用的API有decodeFile,decodeResource,decodeStream,decodeByteArray。
高效的加载大图主要策略是避免图片尺寸超过控件所需的尺寸。我们可以通过设定BitmapFactory.Option中的inSampleSize来修改图片比例,如果将inSample设置为2,那么宽高缩小为原来的1/2,像素缩小为原来的1/4,那么对内存的需求也就缩小为原来的1/4,这样可以有效避免OOM。那么我们怎么通过修改inSampleSize来缩小图片呢?
1.将BitmapFactory.Options中的inJustDecodeBounds设置为true。
2.从BitmapFactory.Options取出图片属性。
3.根据获得的属性与控件属性进行对比采样,计算出合适的inSampleSize(系统规定为2的指数)。
4.将BitmapFactory.Options中的inJustDecodeBounds设置为false,重新加载图片。
代码操作如下:
public Bitmap decodeSampleBitmapFromResource(Resources 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 int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){
if(reqWidth == 0 || reqHeight == 0){
return 1;
}
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;
}