Reputation: 385
How can I convert a HTML code into a PNG image which is transparent?
String s = "<font size="6">Schriftgröße 6</font>"
Convert into transparent image? How can I do this?
Upvotes: 1
Views: 2995
Reputation: 347214
The core problem is, the means by which a html text is renderer is buried WAY deep down in the core API. Been to lazy to go around trying to dig it out, I'd cheat and simply use a JLabel
, for 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();
}
If you'd like to use the html2image API, you'll need to change the way in which the rendering surface it uses is generated.
The API basically uses a JEditorPane
, which is actually a nice trick, the problem is, you need to make it transparent, maybe something like...
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");
Which outputs...
Upvotes: 1