convert html to image in byte array java

江枫思渺然 提交于 2019-12-28 05:42:41

问题


How can i easily convert html to image and then to byte array without create it

thanks


回答1:


If you do not have any complex html you can render it using a normal JLabel. The code below will produce this image:

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

    ....
}

If you would like to just write it to a file:

    ImageIO.write(image, "png", new File("test.png"));



回答2:


I think you can use the library

html2image-0.9.jar

you can download this library at this page: http://code.google.com/p/java-html2image/




回答3:


What about using an in memory ByteArrayStream instead of a FileOutputStream in the code above? That would be a byte array, at least ...




回答4:


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


来源:https://stackoverflow.com/questions/4437806/convert-html-to-image-in-byte-array-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!