在 Java 圖像處理中,為圖片添加水印是版權保護與品牌標識的常見需求。本文提供兩種核心水印實現方案:圖片水印(將 Logo 或簽名圖疊加到目標圖片)與文字水印(繪製版權聲明、時間戳等文本),代碼基於 `java.awt`、`javax.imageio` 與 `com.sun.image.codec.jpeg` 套件,可直接整合至專案中。
統一封裝水印邏輯,提供靜態方法供外部調用,支援 JPEG 格式輸出。
public final static void pressImage(String pressImg, String targetImg, int x, int y) {
try {
// 讀取目標圖片
File _file = new File(targetImg);
Image src = ImageIO.read(_file);
int width = src.getWidth(null);
int height = src.getHeight(null);
// 創建畫布
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, width, height, null);
// 讀取水印圖片
File _filebiao = new File(pressImg);
Image src_biao = ImageIO.read(_filebiao);
int width_biao = src_biao.getWidth(null);
int height_biao = src_biao.getHeight(null);
// 計算位置(右下角偏移 x, y)並繪製
g.drawImage(src_biao, width - width_biao - x, height - height_biao - y, width_biao, height_biao, null);
// 輸出
g.dispose();
FileOutputStream out = new FileOutputStream(targetImg);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
關鍵點:
public static void pressText(String pressText, String targetImg,
String fontName, int fontStyle, int color, int fontSize, int x, int y) {
try {
File _file = new File(targetImg);
Image src = ImageIO.read(_file);
int width = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, width, height, null);
// 設定字體與顏色
g.setColor(new Color(color));
g.setFont(new Font(fontName, fontStyle, fontSize));
// 繪製文字(右下角偏移)
g.drawString(pressText, width - fontSize - x, height - fontSize / 2 - y);
g.dispose();
FileOutputStream out = new FileOutputStream(targetImg);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
參數說明:
public static void main(String[] args) {
// 圖片水印測試
pressImage("pressImg.jpg", "targetImg.jpg", 20, 20);
// 文字水印測試範例
// pressText("© 2024 MyBrand", "targetImg.jpg", "微軟正黑體", Font.BOLD, Color.WHITE.getRGB(), 24, 10, 10);
}