public final class BitmapUtil {
private BitmapUtil() {
}
public static Bitmap loadBitmapWithScale(
File imageFile,
int reqWidth,
int reqHeight) {
Bitmap ret = null;
if (imageFile != null && imageFile.exists() && imageFile.canRead()) {
if (reqWidth >= 0 && reqHeight >= 0) {
String filePath = imageFile.getAbsolutePath();
// 1. 第一次采样
BitmapFactory.Options options = new BitmapFactory.Options();
// 只获取尺寸
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// 2. 获取图片原始尺寸, 计算采样数值
options.inSampleSize = calcInSampleSize(options, reqWidth, reqHeight);
// 3. 再次设置,加载图像到内存
options.inJustDecodeBounds = false;
// 4. TODO: 可以使用 inPreferredConfig 来进一步降低图片像素内存
// 所有的 PNG 图片,都可以支持透明
// 所有的 JPG 图片,都不支持透明
String type = options.outMimeType;
if (type != null) {
// 根据 MIME type 来判断图像的文件格式
// image/png
// image/jpeg
if(type.endsWith("png")){
options.inPreferredConfig = Bitmap.Config.ARGB_4444;
}else if(type.endsWith("jpeg")){
options.inPreferredConfig = Bitmap.Config.RGB_565;
}
}
ret = BitmapFactory.decodeFile(filePath, options);
}
}
return ret;
}
private static int calcInSampleSize(
BitmapFactory.Options op,
int reqWidth,
int reqHeight) {
int inSampleSize = 1;
int outWidth = op.outWidth;
int outHeight = op.outHeight;
if(reqWidth > 0 && reqHeight > 0){
int halfW = outWidth >> 1;
int halfH = outHeight >> 1;
while ((halfW / inSampleSize) >= reqWidth
&& (halfH / inSampleSize) >= reqHeight){
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
android图片压缩
最新推荐文章于 2021-08-12 01:07:14 发布