實現思路
- 讀取源圖片與水印圖片為
Image 對象。
- 創建同尺寸的
BufferedImage 作為畫布。
- 獲取
Graphics2D 畫筆,繪製源圖片。
- 計算水印位置(示例為居中),繪製水印圖片。
- 釋放畫筆資源,將畫布編碼輸出為 JPEG 文件。
完整代碼
try {
String targetImg = "D:/Blue hills.jpg";
String pressImg = "D:/html_original.jpg";
File f1 = new File(targetImg);
Image src = ImageIO.read(f1);
int width = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.drawImage(src, 0, 0, width, height, null);
File f2 = new File(pressImg);
Image srcMark = ImageIO.read(f2);
int markWidth = srcMark.getWidth(null);
int markHeight = srcMark.getHeight(null);
// 居中繪製水印
g.drawImage(srcMark, (width - markWidth) / 2, (height - markHeight) / 2, markWidth, markHeight, null);
g.dispose();
FileOutputStream out = new FileOutputStream(targetImg);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
System.out.println("水印添加成功!!");
} catch (Exception e) {
System.out.println("水印添加失敗!!");
e.printStackTrace();
}
關鍵 API 說明
ImageIO.read(File):支持 JPEG、PNG、BMP 等格式讀取。
BufferedImage.TYPE_INT_RGB:8位RGB色彩模型,適合 JPEG 輸出。
Graphics2D.drawImage(Image, x, y, width, height, observer):縮放繪製,座標以畫布左上角為原點。
JPEGCodec.createJPEGEncoder(OutputStream):將 BufferedImage 編碼為 JPEG 流(屬於 com.sun.image.codec.jpeg 內部包,生產環境建議改用 ImageIO.write())。
進階擴展
- 添加透明度控制:使用
AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)。
- 支持文字水印:
g.drawString(text, x, y) 配合 Font、Color。
- 水印旋轉:
g.rotate(Math.toRadians(angle), cx, cy)。