Jiyeon Jiyeon - 1 year ago 84
Java Question

In Java is it possible to convert a BufferedImage to an IMG Data URI?

I have created a graphical image with the following sample code.

BufferedImage bi = new BufferedImage(50,50,BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2d = bi.createGraphics();

// Draw graphics.

// BufferedImage now has my image I want.

At this point I have BufferedImage which I want to convert into an IMG Data URI. Is this possible? For example..

<IMG SRC="data:image/png;base64,[BufferedImage data here]"/>

Answer Source

Not tested, but something like this ought to 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 lots of different base64 codec implementations for Java. I've had good results with MigBase64.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download