convert html to image in byte array java

cls picture cls · Dec 14, 2010 · Viewed 33k times · Source

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

thanks

Answer

dacwe picture dacwe · Dec 14, 2010

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