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

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.


You could use this solution which doesn't use any external libraries. Short and clean! It uses a Java 6 library (DatatypeConverter). Worked for me!

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