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

Java HTML 轉圖片實現透明背景:修改 html2image 庫源碼

     編輯:Java 相關知識

html2image 庫預設輸出白底圖片,若需透明背景(如疊加水印、UI 合成),需修改其內部 JEditorPane 背景屬性。本文示範下載源碼、修改 createJEditorPane()、重新打包 JAR 的完整流程。

原始簡單用法

HtmlImageGenerator generator = new HtmlImageGenerator();
generator.loadHtml("

Hello

"); generator.saveAsImage("output.png"); // 白底

問題分析

  • 庫內部使用 JEditorPane 渲染 HTML。
  • JEditorPane 預設背景不透明(白色)。
  • 官方 API 無設定背景透明參數。

修改源碼步驟

1. 取得源碼

從 html2image-0.9.jar 解壓或專案官網下載源碼,找到 gui.ava.html.image.generator.HtmlImageGenerator。

2. 修改 createJEditorPane() 方法

protected JEditorPane createJEditorPane() {
    final JEditorPane editorPane = new JEditorPane();
    // 關鍵:設定背景透明(RGBA 全 0)
    editorPane.setBackground(new Color(0, 0, 0, 0));
    editorPane.setOpaque(false);  // 確保不繪製背景

    editorPane.setSize(getDefaultSize());
    editorPane.setEditable(false);
    final SynchronousHTMLEditorKit kit = new SynchronousHTMLEditorKit();
    editorPane.setEditorKitForContentType("text/html", kit);
    editorPane.setContentType("text/html");
    editorPane.addPropertyChangeListener(evt -> {
        if ("page".equals(evt.getPropertyName())) onDocumentLoad();
    });
    return editorPane;
}

3. 重新編譯打包

# 編譯
javac -cp "html2image-0.9.jar" gui/ava/html/image/generator/HtmlImageGenerator.java

# 打包新 JAR
jar uf html2image-0.9.jar gui/ava/html/image/generator/HtmlImageGenerator.class

4. 使用修改後的 JAR

java -cp ".:html2image-0.9.jar" YourMainClass

輸出圖片即為透明背景 PNG。

替代方案:無源碼時用 Java2D 後處理

BufferedImage src = ImageIO.read(new File("white.png"));
BufferedImage transparent = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = transparent.createGraphics();
g2d.drawImage(src, 0, 0, null);
// 將白色像素轉透明(簡易版,實際建議用閾值)
for (int x = 0; x < src.getWidth(); x++)
    for (int y = 0; y < src.getHeight(); y++)
        if (src.getRGB(x, y) == Color.WHITE.getRGB())
            transparent.setRGB(x, y, 0x00FFFFFF);
g2d.dispose();
ImageIO.write(transparent, "PNG", new File("transparent.png"));

注意事項

  • 修改後的 JAR 版本號建議改為 0.9.1-transparent 避免衝突。
  • HTML 中若有 CSS background: white 仍會蓋過透明,需在 HTML 移除或覆寫 body { background: transparent !important; }。
  • html2image 專案已停止維護,新專案建議改用 Flying Saucer (xhtmlrenderer) 或 Puppeteer/Playwright (Headless Chrome) 獲得更完善的 CSS 支援與透明背景原生選項。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved