首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 圖片水印實戰:圖片水印與文字水印完整代碼實現

     編輯:Java 相關知識

在 Java 圖像處理中,為圖片添加水印是版權保護與品牌標識的常見需求。本文提供兩種核心水印實現方案:圖片水印(將 Logo 或簽名圖疊加到目標圖片)與文字水印(繪製版權聲明、時間戳等文本),代碼基於 `java.awt`、`javax.imageio` 與 `com.sun.image.codec.jpeg` 套件,可直接整合至專案中。

核心工具類:ImageUtils

統一封裝水印邏輯,提供靜態方法供外部調用,支援 JPEG 格式輸出。

1. 圖片水印:pressImage 方法

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();
    }
}

關鍵點:

  • 使用 `BufferedImage.TYPE_INT_RGB` 建立不透明畫布,避免透明通道導致背景變黑。
  • 座標計算 `width - width_biao - x` 實現右下角定位,`x、y` 為邊距偏移量。
  • 編碼器採用 `JPEGCodec`,需確保 `rt.jar` 在類路徑中(JDK 內建)。

2. 文字水印:pressText 方法

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);
    }
}

參數說明:

  • `fontName`:字體名稱(如 "微軟正黑體", "Serif")
  • `fontStyle`:`Font.PLAIN`、`Font.BOLD`、`Font.ITALIC` 或組合
  • `color`:RGB 整數值(如 `Color.RED.getRGB()` 或 `0xFF0000`)
  • `fontSize`:字體大小(像素)
  • `x、y`:右下角水平、垂直偏移量

3. 測試入口

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);
}

進階優化建議

  1. 支援透明度:使用 `AlphaComposite` 實現半透明水印,避免遮擋原圖細節。
  2. 多格式支援:利用 `ImageIO.getImageWritersByFormatName` 動態選擇編碼器,支援 PNG、BMP 等格式並保留透明通道。
  3. 文字換行與自適應:長文本可透過 `FontMetrics` 計算寬高自動換行或縮放字體。
  4. 性能優化:大批量處理時複用 `BufferedImage` 與 `Graphics`,減少對象創建開銷。
  5. 異常處理細化:區分文件不存在、格式不支援、IO 錯誤等異常類型,提供更精確的錯誤碼。

依賴與兼容性提示

  • `com.sun.image.codec.jpeg` 屬 Sun 專有 API,JDK 9+ 已移除。現代專案建議遷移至 `javax.imageio.plugins.jpeg` 或第三方庫(如 TwelveMonkeys ImageIO)。
  • 若需跨平台字體渲染一致性,建議打包 TTF 字體檔並透過 `Font.createFont` 載入。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved