如何加载图片?
主要是通过BitmapFactory类提供方法加载图片:
decodeFile:从文件系统中加载
decodeResource:从资源中加载
decodeStream:从输入流中加载
decodeByteArray:从字节数组中加载
如何高效加载Bitmap?
采用BitmapFactory.Options来加载所需尺寸的图片,可以按一定的采样率来加载缩小的图片,将缩小的图片在ImageView中显示。
具体实现流程:
a. 将BitmapFactory.Options中的inJustDecodeBounds参数设置为true并加载图片
b. 从BitmapFactory.Options中获取到图片的原始宽高信息
c. 根据采样率规则并结合目标view的所需大小计算出采样率inSampleSize
d. 将BitmapFactory.Options的inJustDecodeBounds参数设为false,然后重新加载
注意:这里设置BitmapFactory.Options为true时,只会获取到图片的宽高信息,这样的操作是轻量级的。
实现代码:
/**
* 根据内部资源来压缩图片
* @param res 传入的资源
* @param resId 传入对应的id
* @param reqWidth 所需的宽度
* @param reqHeight 所需的高度
* @return
*/
public Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight){
final BitmapFactory.Options options = new BitmapFactory.Options();
//设置为true,表示只获取图片的尺寸
options.inJustDecodeBounds = true;
//计算压缩比
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
//设置为false,表示获取图片的所有信息
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
if (reqHeight == 0 || reqWidth == 0)
return 1;
//获取到图片的原始宽高
final int width = options.outWidth;
final int height = options.outHeight;
int inSampleSize = 1;
//计算压缩比,一般设置为1,2,4等2的次方数
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;
}
调用方法:
imageView.setImageBitmap(decodeSampledBitmapResource(getResource(), R.id.image,100,100));
网友评论