convert html to image in byte array java

后端 未结 4 1929
-上瘾入骨i
-上瘾入骨i 2020-12-05 12:49

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

thanks

相关标签:
4条回答
  • 2020-12-05 12:51

    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>
    

    alt text

    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"));
    
    0 讨论(0)
  • 2020-12-05 12:53

    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();
    }
    
    0 讨论(0)
  • 2020-12-05 13:02

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

    0 讨论(0)
  • 2020-12-05 13:16

    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/

    0 讨论(0)
提交回复
热议问题