public class BitmapUtils {
public static Bitmap decodeSampledBitmapFromResource(String filePath,
int reqWidth, int reqHeight) {
//加载图片的边界信息(只读取图片的高度,宽度,不读取具体字节)
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options =
new BitmapFactory.Options();
//将此选项设置true,此时再加载图片就会只读取图片边界信息了。
options.inJustDecodeBounds = true;
//加载图片边界,并将边界信息封装到options对象
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize(计算压缩比例)
options.inSampleSize =
calculateInSampleSize(options,
reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
/**计算压缩比例*/
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
//获得实际图片的高度,宽度
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
//通过实际的高度,宽度与我们需要的高度,宽度进行比例运算得到一个压缩比例值
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;//高度和宽度都按照此比例进行压缩
}