// 对于图片压缩,主要针对大图片,这里的压缩是采取先解码尺寸,然后计算压缩比,整数倍压缩方式,所以是近似结果;
public static Bitmap getZoomImage(String filename, int outWidth, int outHeight) {
FileInputStream fs = null;
BufferedInputStream bs = null;
try {
fs = new FileInputStream(filename);
bs = new BufferedInputStream(fs);
BitmapFactory.Options options = setBitmapOption(filename, outWidth, outHeight);
return BitmapFactory.decodeStream(bs, null, options);
} catch (Exception e) {
LogUtil.i(TAG, e);
} finally {
try {
bs.close();
fs.close();
} catch (Exception e) {
LogUtil.i(TAG, e);
}
}
return null;
}
private static BitmapFactory.Options setBitmapOption(String file, int outWidth, int outHeight) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
// 设置只是解码图片的边距,此操作目的是度量图片的实际宽度和高度
BitmapFactory.decodeFile(file, opt);
int origWidth = opt.outWidth; // 获得图片的实际高和宽
int origHeight = opt.outHeight;
opt.inDither = false;
opt.inPreferredConfig = Bitmap.Config.RGB_565;
LogUtil.i(TAG, "原始信息 " + StringUtils.formatKeyValue("origWidth", "" + origWidth) + StringUtils.formatKeyValue("origHeight", "" + origHeight));
LogUtil.i(TAG, "目标信息 " + StringUtils.formatKeyValue("outWidth", "" + outWidth) + StringUtils.formatKeyValue("outHeight", "" + outHeight));
// 设置加载图片的颜色数为16bit,默认是RGB_8888,表示24bit颜色和透明通道,但一般用不上
opt.inSampleSize = 1;
// 设置缩放比,1表示原比例,2表示原来的四分之一....
// 计算缩放比
if (origWidth != 0 && origHeight != 0 && outWidth != 0 && outHeight != 0) {
int sampleSize = (int) (Math.max((float) origWidth / (float) outWidth, (float) origHeight / (float) outHeight) + 0.5f);
if (sampleSize < 1) {
sampleSize = 1;
}
opt.inSampleSize = sampleSize;
}
LogUtil.i(TAG, StringUtils.formatKeyValue("inSampleSize", "" + opt.inSampleSize));
opt.inJustDecodeBounds = false;// 最后把标志复原
return opt;
}