不改變圖片的分辨率大小,即圖片始終為200x300。
/**
* 把Bitmap進行壓縮保存成文件
* 圖片最終的格式為jpg
*
* @param dirPath 保存圖片的目錄
* @param filename 保存圖片的文件名
* @param bitmap 要保存成文件的bitmap
* @param maxKB 圖片質量的最大值,單位為KB【壓縮的閾值】
*/
public static boolean saveBitmapToFile(@NonNull String dirPath, @NonNull String filename,
@NonNull Bitmap bitmap, @NonNull int maxKB) {
if (maxKB <= 0) {
return false;
}
if (TextUtils.isEmpty(dirPath) || TextUtils.isEmpty(filename) || bitmap == null) return false;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//質量壓縮方法,這里100表示不壓縮,把壓縮后的數據存放到baos中
int options = 100;
while (baos.size() / 1024 > maxKB) { //循環判斷如果壓縮后圖片是否大于maxKB,大于繼續壓縮
baos.reset();//重置清空baos
options -= 10;//質量壓縮比例減10
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//壓縮options%,把壓縮后的數據存放到baos中
}
FileOutputStream out = null;
try {
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dirPath, filename);
if (file.exists()) {
file.delete();
}
file.createNewFile();
out = new FileOutputStream(file);
baos.writeTo(out);
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
CloseableUtil.closeSilently(out);
CloseableUtil.closeSilently(baos);
}
return true;
}