// 获取压缩后的图片地址
// 进行尺寸压缩之后再进行质量压缩
public static String getCompressedPath(Context context, String path) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 获取图片的宽高,图片并没有加载进内存
BitmapFactory.decodeFile(path, options);
int originWidth = options.outWidth;
int originHeight = options.outHeight;
// 目标尺寸的宽高根据具体情况来定
float targetHeight = 1024f;
float targetWidth = 1024f;
int rate = 1; // rate=1表示不缩放
if (originWidth >= originHeight && originWidth > targetWidth) { // 如果宽度大的话根据宽度固定大小缩放
rate = (int) (options.outWidth / targetWidth);
} else if (originWidth < originHeight && originHeight > targetHeight) { // 如果高度高的话根据宽度固定大小缩放
rate = (int) (options.outHeight / targetHeight);
}
if (rate <= 0) rate = 1;
options.inSampleSize = rate; // 设置缩放比例
options.inJustDecodeBounds = false; // 这里一定要将其设置回false,因为之前我们将其设置成了true
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
String name = String.valueOf(System.currentTimeMillis());
File uploadImageDir = new File(getUploadImageDir(context));
File uploadImageFile = new File(uploadImageDir + "/" + name + ".jpg"); // 压缩后的图片位置
if (!uploadImageDir.exists()) {
uploadImageDir.mkdirs();
} else {
if (uploadImageFile.exists()) {
uploadImageFile.delete();
}
}
try {
FileOutputStream out = new FileOutputStream(uploadImageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out); // 进行质量压缩
out.flush();
out.close();
bitmap.recycle(); // 回收bitmap,节省内存
return uploadImageFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
return null;
}
Android图片压缩,先进行尺寸压缩,再质量压缩
最新推荐文章于 2020-12-09 23:06:06 发布