Android 繪圖核心在於 Canvas(畫布)與 Bitmap(位圖)。利用離屏 Bitmap 作為雙緩衝,可實現高效合成、水印疊加、縮放並最終儲存圖檔。
Config.ARGB_8888 為 32 位真彩色;save()/restore() → 結果保留在 Bitmap 中。private Bitmap createWatermarkedBitmap(Bitmap src, Bitmap watermark) {
if (src == null) return null;
int w = src.getWidth(), h = src.getHeight();
int ww = watermark.getWidth(), wh = watermark.getHeight();
// 1. 建立目標 Bitmap(與來源同尺寸)
Bitmap result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
// 2. 繪製基底圖
canvas.drawBitmap(src, 0, 0, null);
// 3. 繪製水印(右下角偏移 5px)
canvas.drawBitmap(watermark, w - ww + 5, h - wh + 5, null);
// 4. 提交所有圖層
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return result;
}
private Bitmap scaleBitmap(Bitmap src, int dstWidth, int dstHeight) {
if (src == null) return null;
float scaleX = (float) dstWidth / src.getWidth();
float scaleY = (float) dstHeight / src.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(scaleX, scaleY);
// 直接依矩陣縮放生成新 Bitmap
return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
}
public boolean saveBitmap(Bitmap bmp, String path) {
File file = new File(path);
try (FileOutputStream fos = new FileOutputStream(file)) {
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos); // 品質 100
fos.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
BitmapFactory.decodeFile,屬不可變,需先 copy() 或建立新 Bitmap 再繪製;inSampleSize 降採樣載入;canvas.save/restore 配合 ALL_SAVE_FLAG 確保所有圖層合併;bitmap.recycle() 釋放原生記憶體(API 11+ 自動管理,但手動釋放更保險)。