7

我如何轻松地将 html 转换为图像,然后转换为字节数组而不创建它

谢谢

4

4 回答 4

13

如果您没有任何复杂的 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"));
于 2010-12-14T10:10:05.430 回答
4

我想你可以使用图书馆

html2image-0.9.jar

你可以在这个页面下载这个库:http ://code.google.com/p/java-html2image/

于 2011-08-18T00:04:58.097 回答
3

在上面的代码中使用内存ByteArrayStream而不是 a怎么样?FileOutputStream那将是一个字节数组,至少......

于 2012-11-26T22:00:02.890 回答
0

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();
}
于 2010-12-14T09:56:49.090 回答