Convert BufferedImage to Byte Array in Java

Convert BufferedImage to byte array in Java

In this article, we will see how to convert BufferedImage to Byte Array in Java.

💡 Outline

To convert BufferedImage to byte array, you can use below code:

Java BufferedImage to Byte Array

Here are steps to convert BufferedImage to Byte Array in java:

  • Create instance of ByteArrayOutputStream baos.
  • Call ImageIo.write() with bufferedImage, formatName such as png,jpg etc. and baos as parameters
  • Get byte array from ByteArrayOutputStream baos by calling toByteArray() method.

Here is complete program:

Convert BufferedImage to byte[] without writing to disk

In case you have large amount of BufferedImages and do not want to write to disk, you can use following code as per this stackoverflow thread.
{!{pre code="java" title="BufferedImage to byte[] without writing to disk"}!}czo5MzpcIg0KYnl0ZVtdIGltYWdlQnl0ZXMgPSAoKERhdGFCdWZmZXJCeXRlKSBidWZmZXJlZEltYWdlLmdldERhdGEoKS5nZXREYXR7WyYqJl19YUJ1ZmZlcigpKS5nZXREYXRhKCk7DQpcIjt7WyYqJl19{!{/pre}!}

Above code will create copy of image. If you are looking for direct reference you can use bufferedImage.getRaster().getDataBuffer().

That’s all about how to Convert BufferedImage to Byte Array in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *