Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert html to image in byte array java

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

thanks

like image 387
cls Avatar asked Dec 14 '10 09:12

cls


People also ask

How do I save a byte array as a picture?

Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter). Finally, Write the image to using the write() method of the ImageIo class.

How to convert ByteArrayOutputStream to image in java?

Create the object of the ByteArrayOutputStream class and write the image into that which we have read in the above step. ByteArrayOutputStream outStreamObj = new ByteArrayOutputStream(); ImageIO. write(image, "jpg", outStreamObj); Convert the image into the byte array.

How do you turn a picture into a byte?

Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.


2 Answers

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"));
like image 85
dacwe Avatar answered Sep 23 '22 20:09

dacwe


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/

like image 39
Edwin Pomayay Yaranga Avatar answered Sep 22 '22 20:09

Edwin Pomayay Yaranga