将html转换为字节数组java中的图像

cls*_*cls 7 html java image renderer layout-engine

我怎样才能轻松地将html转换为图像然后转换为字节数组而不创建它

谢谢

dac*_*cwe 14

如果您没有任何复杂的html,可以使用法线渲染它JLabel.下面的代码将生成此图像:

<html>
  <h1>:)</h1>
  Hello World!<br>
  <img src="http://img0.gmodules.com/ig/images/igoogle_logo_sm.png">
</html>
Run Code Online (Sandbox Code Playgroud)

替代文字

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();

    ....
}
Run Code Online (Sandbox Code Playgroud)

如果您想将其写入文件:

    ImageIO.write(image, "png", new File("test.png"));
Run Code Online (Sandbox Code Playgroud)


Wou*_*ens 0

这并不简单,因为渲染 HTML 页面可能非常复杂:您需要评估文本、图像、CSS,甚至可能是 JavaScript。

我不知道答案,但我确实有一些可以帮助您的东西:用于将 HTML 页面转换为 PDF 文件的 iText(PDF 书写库)代码。

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();
}
Run Code Online (Sandbox Code Playgroud)