Convert Image to byte array in Java

  final Image image = ...;
  final ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try {
    final BufferedImage bufferedImage = createBufferedImageFrom(image);
    ImageIO.write(bufferedImage, "png", baos);
  } finally {
  return baos.toByteArray();

private BufferedImage createBufferedImageFrom(final Image image) {
  if (image instanceof BufferedImage) {
    return (BufferedImage) image;
  } else {
    final BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null),
    final Graphics2D g2 = bi.createGraphics();
    g2.drawImage(image, 0, 0, null);
    return bi;

If you don’t want to make use of IOUtils from Apache Commons Lang, you should you know, the code in the finally block would be something like

try {
  if (baos != null) {
} catch (IOException ioe) {
  // ignore

One thought on “Convert Image to byte array in Java

Leave a Reply