convert html to image in byte array java

后端 未结 4 1931
-上瘾入骨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:

    
      

    :)

    Hello World!

    alt text

    public static void main(String... args) throws IOException {
    
        String html = "" +
                "

    :)

    " + "Hello World!
    " + "" + ""; 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"));
    

提交回复
热议问题