bas*_*mes 7 html java graphics rendering image
我有一个小的HTML模板,我必须使用它创建一个图像.HTML由文本和格式组成.生成的图像由其他服务使用.它类似于零售商店的产品价格显示.
是否有可以渲染HTML
到图像文件或字节数组的Java库?我看过眼镜蛇,但看起来很旧.
编辑:设置基本的HTML到JLabel和使用BufferedImage应该工作,但我不确定CSS和样式的东西是否会得到妥善处理.
样品风格
<styles> width:"240",height:"96",background:{type:"solid",color:"#ffffff"} </ styles>
小智 5
您好,我使用HTML2Image来实现此目的。
这很简单:
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml("<b>Hello World!</b> Please goto <a title=\"Goto Google\" href=\"http://www.google.com\">Google</a>.");
imageGenerator.saveAsImage("hello-world.png");
imageGenerator.saveAsHtmlWithMap("hello-world.html", "hello-world.png");
Run Code Online (Sandbox Code Playgroud)
我的解决方案包括3个步骤
BufferedImage
并创建它Graphics
JEditorPane
并调用print(Graphics)
BufferedImage
通道ImageIO
码:
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JEditorPane;
public class Test {
public static void main(String[] args) {
String html = "<h1>Hello, world.</h1>Etc. Etc.";
int width = 200, height = 100;
// Create a `BufferedImage` and create the its `Graphics`
BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration()
.createCompatibleImage(width, height);
Graphics graphics = image.createGraphics();
// Create an `JEditorPane` and invoke `print(Graphics)`
JEditorPane jep = new JEditorPane("text/html", html);
jep.setSize(width, height);
jep.print(graphics);
// Output the `BufferedImage` via `ImageIO`
try {
ImageIO.write(image, "png", new File("Image.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果: