電商專案裡,商品圖往往要加上浮水印避免被盜用。需求通常有兩種:貼一張 logo 圖片,或直接寫一行文字。Java 標準庫的 javax.imageio 搭配 Graphics2D 就能完成,不必引入第三方依賴。
package com.blogs.image;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
* 圖片浮水印工具
*/
public class ImageUtil {
public static void main(String[] args) {
String srcImgPath = "e:/2.png";
String iconPath = "e:/logo.jpg";
String targerPath = "e:/3.jpg";
// 加上圖片浮水印
ImageUtil.waterMarkImageByIcon(iconPath, srcImgPath, targerPath, 0, 0, 0, 0.1f);
// 若要旋轉 -45 度,可改呼叫旋轉版本
// ImageMarkLogoByIcon.markImageByIcon(iconPath, srcImgPath, targerPath2, -45);
}
/**
* 為圖片加上圖片浮水印,可設定旋轉角度
*
* @param iconPath 浮水印圖片路徑
* @param srcImgPath 來源圖片路徑
* @param targerPath 輸出圖片路徑
* @param degree 浮水印旋轉角度
* @param width 與左側的偏移
* @param height 與頂部的偏移
* @param clarity 透明度,小於 1,越接近 0 越透明
*/
public static void waterMarkImageByIcon(String iconPath, String srcImgPath,
String targerPath, Integer degree,
Integer width, Integer height,
float clarity) {
OutputStream os = null;
try {
Image srcImg = ImageIO.read(new File(srcImgPath));
System.out.println("width:" + srcImg.getWidth(null));
System.out.println("height:" + srcImg.getHeight(null));
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
// 取得畫筆
Graphics2D g = buffImg.createGraphics();
// 設定線段鋸齒處理,讓縮放後的影像較平滑
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),
srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
if (null != degree) {
// 以圖片中心為軸旋轉
g.rotate(Math.toRadians(degree),
(double) buffImg.getWidth() / 2,
(double) buffImg.getHeight() / 2);
}
// 浮水印建議用 gif 或 png,才能設定透明度
ImageIcon imgIcon = new ImageIcon(iconPath);
Image img = imgIcon.getImage();
float alpha = clarity;
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
// 繪製浮水印於指定座標
g.drawImage(img, width, height, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
g.dispose();
os = new FileOutputStream(targerPath);
ImageIO.write(buffImg, "JPG", os);
System.out.println("添加浮水印圖片完成!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != os) os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 為圖片加上文字浮水印,可設定旋轉角度
*/
public static void waterMarkByText(String logoText, String srcImgPath,
String targerPath, Integer degree,
Integer width, Integer height,
Float clarity) {
InputStream is = null;
OutputStream os = null;
try {
Image srcImg = ImageIO.read(new File(srcImgPath));
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),
srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
if (null != degree) {
g.rotate(Math.toRadians(degree),
(double) buffImg.getWidth() / 2,
(double) buffImg.getHeight() / 2);
}
g.setColor(Color.red);
g.setFont(new Font("新細明體", Font.BOLD, 30));
float alpha = clarity;
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
// 第三、四參數為文字在圖片上的座標 (x, y)
g.drawString(logoText, width, height);
g.dispose();
os = new FileOutputStream(targerPath);
ImageIO.write(buffImg, "JPG", os);
System.out.println("添加浮水印文字完成!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (null != is) is.close(); } catch (Exception e) { e.printStackTrace(); }
try { if (null != os) os.close(); } catch (Exception e) { e.printStackTrace(); }
}
}
}
/**
* 圖片等比例縮放為指定大小,空白處以白色填滿
*/
public static void zoomImage(String srcPath, String destPath,
int destHeight, int destWidth) {
try {
BufferedImage srcBufferedImage = ImageIO.read(new File(srcPath));
int imgWidth = destWidth;
int imgHeight = destHeight;
int srcWidth = srcBufferedImage.getWidth();
int srcHeight = srcBufferedImage.getHeight();
if (srcHeight >= srcWidth) {
imgWidth = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
} else {
imgHeight = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
}
BufferedImage destBufferedImage =
new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = destBufferedImage.createGraphics();
graphics2D.setBackground(Color.WHITE);
graphics2D.clearRect(0, 0, destWidth, destHeight);
graphics2D.drawImage(
srcBufferedImage.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH),
(destWidth / 2) - (imgWidth / 2),
(destHeight / 2) - (imgHeight / 2), null);
graphics2D.dispose();
ImageIO.write(destBufferedImage, "JPEG", new File(destPath));
} catch (IOException e) {
e.printStackTrace();
}
}
浮水印建議用 PNG 而非 JPG。JPG 是無失真壓縮、不支援 Alpha 通道,用來當浮水印會帶著白色底,蓋在主圖上很突兀。GIF 與 PNG 才有透明通道。
輸出 JPG 時透明會變黑。TYPE_INT_RGB 沒有 Alpha 通道,任何透明區域轉存 JPG 都會被填成黑色。若需要保留透明,輸出格式應改為 PNG 並使用 TYPE_INT_ARGB。
Graphics2D 一定要 dispose。它持有系統資源,不釋放會造成記憶體累積,在批次處理大量圖片時尤其明顯。用 try-with-resources 無法直接套用(Graphics2D 未實作 AutoCloseable),但仍應放在 finally 中確保釋放。
浮水印位置應可參數化。寫死 (0, 0) 容易被裁切規避,實務上常做九宮格定位或全圖平鋪鋪水印,並加入輕微隨機偏移提高移除成本。
Font 名稱要跨平台。範例原用「宋體」,在 Linux 或無字型環境會 fallback 成預設字型甚至亂碼。建議改用 Font.getName() 偵測可用字型,或改用 GraphicsEnvironment.getAvailableFontFamilyNames() 挑一個存在的。