1.图片加载
BitmapFactory类提供了四种加载的方法:decodeFile,decodeResource,decodeStream,decodeByteArray,分别支持从文件、资源、输入流以及字节数组来加载Bitmap对象,其中decodeFile,decodeResource又间接调用了decodeStream方法,这四类方法最终在Android的底层实现,对应着BitmapFactory类的几个native方法。
2.高效加载Bitmap
采用BitmapFactory.Options来加载所需要尺寸的图片。通过BitmapFactory.Options可以按照一定的采样率来加载缩小后的图片,然后将缩小后的图片加载在控件上。降低内存避免OOM,BitmapFactory加载图片的四种方法都支持BitmapFactory.Options参数。
3.BitmapFactory.Options缩放图片
图片的缩放主要使用了它的参数inSampleSize,即采样率。当采样率为1时,采样后的图片为图片的原始大小;当采样率为2时,采样后的图片宽高为原来的1/2,像素数为原来的1/4,其占有的内存也为原来的1/4。采样率是必须大于1的整数才会有缩小的效果,并且采样率同时作用于宽高,这将导致缩放后的图片大小以采样率的2次方形式递减。官方文档上指出,inSampleSize的取值应该为2的指数,如果不为2的指数,系统会向下取整并选择一个最接近2的指数来代替,比如3,系统会选择2,但是经过验证,这个结论并非在所有的Android版本中使用,可以作为一个参考建议。
采样遵循以下流程:
(1).将BitmapFactory.Options的参数inJustDecodeBounds参数设为true并加载图片。
(2).从BitmapFactory.Options中取出图片的原始高度和宽度,对应参数outHeight,outWidth。
(3).根据采样率的规则以及目标View需要的宽高计算出采样率inSampleSize的大小。
(4).将BitmapFactory.Options的参数inJustDecodeBounds设为false,并重新加载图片。
补充说明在讲inJustDecodeBounds设为true时,BitmapFactory只会解析图片的原始宽高信息,并不会真的去加载图片,这个操作是轻量级的。
代码如下:
private void initView() {
ImageView iv = (ImageView) findViewById(R.id.activity_main_iv);
ImageResizer imageResizer = new ImageResizer();
imageResizer.decodeSampleBitmapFromResource(getResources(),R.mipmap.ic_launcher,100,100);
}
public class ImageResizer {
public ImageResizer() {
}
public Bitmap decodeSampleBitmapFromResource(Resources resources, int id, int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources, id, options);
options.inSampleSize = calculateInSampleBitmap(reqWidth, reqHeight, options);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(resources, id, options);
}
private int calculateInSampleBitmap(int reqWidth, int reqHeight, BitmapFactory.Options options) {
if(reqHeight==0||reqWidth==0){
return 1;
}
int outWidth = options.outWidth;
int outHeight = options.outHeight;
int intSampleSize = 1;
if (reqWidth < outWidth || reqHeight < outHeight) {
int halfWidth = outWidth / 2;
int halfHeight = outHeight / 2;
while (halfWidth/intSampleSize>=reqWidth &&halfHeight/intSampleSize>=reqHeight){
intSampleSize*=2;
}
}
return intSampleSize;
}
}