單純質量壓縮(JPEG quality)無法改變像素尺寸,大圖易導致 OOM;單純縮放可能質量不足。最佳做法:先按目標尺寸縮放,再質量壓縮。
private Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int quality = 100;
image.compress(Bitmap.CompressFormat.JPEG, quality, baos);
while (baos.toByteArray().length / 1024 > 100) { // 目標 < 100KB
baos.reset();
quality -= 10;
image.compress(Bitmap.CompressFormat.JPEG, quality, baos);
}
return BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()));
}
private Bitmap getImage(String srcPath) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true; // 僅解析尺寸
BitmapFactory.decodeFile(srcPath, opts);
int targetW = 480, targetH = 800; // 目標螢幕尺寸
int be = 1;
if (opts.outWidth > opts.outHeight && opts.outWidth > targetW) {
be = opts.outWidth / targetW;
} else if (opts.outHeight > targetH) {
be = opts.outHeight / targetH;
}
be = Math.max(1, be);
opts.inSampleSize = be;
opts.inJustDecodeBounds = false;
Bitmap scaled = BitmapFactory.decodeFile(srcPath, opts);
return compressImage(scaled); // 再做質量壓縮
}
private Bitmap comp(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
if (baos.toByteArray().length / 1024 > 1024) { // >1MB 先粗略壓縮
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
}
// 再用 inSampleSize 縮放
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, opts);
// ... 計算 inSampleSize 同方法二 ...
opts.inJustDecodeBounds = false;
Bitmap scaled = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, opts);
return compressImage(scaled);
}
inJustDecodeBounds=true 只讀取尺寸,不分配像素記憶體,防 OOM。inSampleSize 為 2 的冪次時效能最佳(解碼器優化)。recycle() 原 Bitmap(API 19+ 自動管理,但手動釋放更保險)。BitmapFactory.decodeStream 搭配 inMutable=true 以便複用記憶體。「先縮放後質量」是通用高效方案,可根據業務調整目標尺寸與 KB 閾值,兼顧清晰度與記憶體安全。