public class ImageUtil {
//图片二次采样
public static Bitmap scaleBitmap(String filePath, int width, int height) {
//进行两次decode
//第一次decode,只解析bitmap的宽高信息
//缩小图片大小, 降低内存占用
BitmapFactory.Options opts = new BitmapFactory.Options();
//指定只解析bitmap的边界信息,不加载bitmap到内存中
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, opts);
//宽高信息
//1920 1080
//256 256
//opts.outWidth;
//opts.outHeight;
//通过图片的真实宽高信息 和 需要的宽高比,产生一个比例
opts.inSampleSize = Math.max(opts.outHeight / height, opts.outWidth / width);
//第二次加载图片: 真正加载图片
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, opts);
return bitmap;
}
//tup质量压缩: 只改变文件大小,基本不改变内存占用
public static Bitmap compress(Bitmap bitmap, int qual, File output) {
Bitmap result = bitmap;
try {
//缩放后的
//bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "tmp.jpg")));
//压缩后的,保存到output文件
bitmap.compress(Bitmap.CompressFormat.JPEG, qual, new FileOutputStream(output));
//再次解析压缩后的图片
result = BitmapFactory.decodeFile(output.getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
};
return result;
}
}