我如何轻松地将 html 转换为图像,然后转换为字节数组而不创建它
谢谢
如果您没有任何复杂的 html,您可以使用普通的JLabel
. 下面的代码将生成此图像:
<html>
<h1>:)</h1>
Hello World!<br>
<img src="http://img0.gmodules.com/ig/images/igoogle_logo_sm.png">
</html>
public static void main(String... args) throws IOException {
String html = "<html>" +
"<h1>:)</h1>" +
"Hello World!<br>" +
"<img src=\"http://img0.gmodules.com/ig/images/igoogle_logo_sm.png\">" +
"</html>";
JLabel label = new JLabel(html);
label.setSize(200, 120);
BufferedImage image = new BufferedImage(
label.getWidth(), label.getHeight(),
BufferedImage.TYPE_INT_ARGB);
{
// paint the html to an image
Graphics g = image.getGraphics();
g.setColor(Color.BLACK);
label.paint(g);
g.dispose();
}
// get the byte array of the image (as jpeg)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] bytes = baos.toByteArray();
....
}
如果您只想将其写入文件:
ImageIO.write(image, "png", new File("test.png"));
在上面的代码中使用内存ByteArrayStream
而不是 a怎么样?FileOutputStream
那将是一个字节数组,至少......
This is nontrivial because rendering a HTML page can be quite complex: you have text, images, CSS, possibly even JavaScript to evaluate.
I don't know the answer, but I do have something that might help you: code for iText (a PDF writing library) to convert a HTML page to a PDF file.
public static final void convert(final File xhtmlFile, final File pdfFile) throws IOException, DocumentException
{
final String xhtmlUrl = xhtmlFile.toURI().toURL().toString();
final OutputStream reportPdfStream = new FileOutputStream(pdfFile);
final ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(xhtmlUrl);
renderer.layout();
renderer.createPDF(reportPdfStream);
reportPdfStream.close();
}