Java BufferedImage to PNG format Base64 String

I followed xehpuk’s answer but had issues with certain images having the last few rows of pixels missing when rendered in certain browsers via a data url (Chrome and Firefox, Safari seemed to render them fine). I suspect this is because the browser is doing it’s best to interpret the data but the last few bytes of data was missing so it shows what it can.

The wrapping of the output stream seems to be the cause of this problem. The documentation for Base64.wrap(OutputStream os) explains:

It is recommended to promptly close the returned output stream after use, during which it will flush all possible leftover bytes to the underlying output stream.

So depending on the length of the data, it’s possible the last few bytes are not flushed from the stream because close() isn’t called on it. My solution to this was to not bother wrapping the stream and just encode the stream directly:

public static String imgToBase64String(final RenderedImage img, final String formatName)
{
  final ByteArrayOutputStream os = new ByteArrayOutputStream();

  try
  {
    ImageIO.write(img, formatName, os);
    return Base64.getEncoder().encodeToString(os.toByteArray());
  }
  catch (final IOException ioe)
  {
    throw new UncheckedIOException(ioe);
  }
}

This resolved the issues with the missing rows of pixels when rendered in a browser.

Leave a Comment