</pre><pre name="code" class="java">public class ImageUtile {
/**
* 将资源图片按照需要显示的大小进行合理压缩,防止程序因图片过大引起的内存溢出,导致程序崩溃
* @param res Resources
* @param resId 资源ID
* @param reqWidth 需要显示的宽度
* @param reqHeight 需要显示的高度
* @return 经过合理压缩后的位图(Bitmap)
*/
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
//将这个参数的inJustDecodeBounds属性设置为true
//就可以让解析方法禁止为bitmap分配内存,返回值也不再是一个Bitmap对象,而是 null
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 计算inSampleSize值
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
/**
* 计算压缩比
* @param options 图片加载配置参数
* @param reqWidth 需要显示的宽度
* @param reqHeight 需要显示的高度
* @return 压缩比
*/
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 heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
// 一定都会大于等于目标的宽和高。
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
}
当然,加载文件图片、流图片等都可以应用此方法,只需要更改BitmapFactory.decodeResource——>BitmapFactory.decodeFile(pathName, opts)等,就可以了