JAVA:将HTML代码转换为透明的图像

时间:2015-11-11 06:29:47

标签: java html image png transparent

如何将HTML代码转换为透明的PNG图像?

<schedulers>
  <Scheduler name="test1" alert="4" timerType="type1" cronExpression="0/10 * * * * ?">
    <property name="customerName" value="COMMON_MODEL" />
  </Scheduler>
  <Scheduler name="test2" alert="3" timerType="type2" cronExpression="0/15 * * * * ?" />
  <Scheduler name="test3" maxFailureAlert="3" timerType="Type3" cronExpression="0/20 * * * * ?" />
  <Scheduler name="test4" maxFailureAlert="3" timerType="Type3" cronExpression="0/50 * * * * ?" />
</schedulers>

转换为透明图片?我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

核心问题是,html文本渲染器的方式深埋在核心API中。去过懒惰试图挖掘它,我作弊,只是使用JLabel,例如......

Example

JLabel label = new JLabel("<html><font size=\"6\">Schriftgröße 6</font></html>");
label.setSize(label.getPreferredSize());

BufferedImage img = new BufferedImage(label.getPreferredSize().width, label.getPreferredSize().height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
label.printAll(g2d);
g2d.dispose();
try {
    ImageIO.write(img, "png", new File("Text.png"));
} catch (IOException ex) {
    ex.printStackTrace();
}

如果您想使用html2image API,则需要更改其使用的渲染表面的生成方式。

API基本上使用JEditorPane,这实际上是一个很好的技巧,问题是,你需要让它透明,可能就像......

HtmlImageGenerator imageGenerator = new HtmlImageGenerator() {
    protected JEditorPane createJEditorPane() {
        JEditorPane editor = super.createJEditorPane();
        editor.setOpaque(false);
        return editor;
    }

};
imageGenerator.loadHtml("<font size=\"6\">Schriftgröße 6</font>");
imageGenerator.saveAsImage("hello-world.png");

哪些输出......

hello-world.png