In Java, can I convert a BufferedImage to an IMG Data URI URI?

I created a graphic with the following code example.

BufferedImage bi = new BufferedImage(50,50,BufferedImage.TYPE_BYTE_BINARY); Graphics2D g2d = bi.createGraphics(); // Draw graphics. g2d.dispose(); // BufferedImage now has my image I want. 

At this point, I have a BufferedImage that I want to convert to IMG data URIs. Is it possible? For instance..

 <IMG SRC="data:image/png;base64,[BufferedImage data here]"/> 
+6
source share
2 answers

Not tested, but something like this should do it:

 ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(bi, "PNG", out); byte[] bytes = out.toByteArray(); String base64bytes = Base64.encode(bytes); String src = "data:image/png;base64," + base64bytes; 

There are many different base64 codec implementations for Java . I had good results with MigBase64 .

+12
source

You can use this solution that does not use external libraries. Short and clean! It uses the Java 6 library ( DatatypeConverter ). Worked for me!

 ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(image, "png", output); DatatypeConverter.printBase64Binary(output.toByteArray()); 
+2
source

Source: https://habr.com/ru/post/890707/


All Articles