核心问题是,html 文本渲染器的方式深埋在核心 API 中。一直懒得四处寻找,我会作弊并简单地使用JLabel,例如...
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");
哪些输出...