Table of Contents
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:
123456 BufferedImage bufferedImage = ImageIO.read(new File("c:\\sample.png"));ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageIO.write(bufferedImage, "png", baos);byte[] byteArr = baos.toByteArray();
Java BufferedImage to Byte Array
Here are steps to convert BufferedImage
to Byte Array
in java:
- Create instance of ByteArrayOutputStream
baos
. - Call
ImageIo.write()
withbufferedImage
, formatName such aspng
,jpg
etc. andbaos
as parameters - Get byte array from ByteArrayOutputStream
baos
by callingtoByteArray()
method.
Here is complete program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package org.arpit.java2blog; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class BufferedImageToByteArray { public static void main(String[] args) throws IOException { Path source = Paths.get("MyFile.png"); BufferedImage bufferedImage = ImageIO.read(source.toFile()); byte[] byteArr = convertBufferImageToByteArray(bufferedImage); System.out.println(byteArr); } // Convert BufferedImage to Byte array public static byte[] convertBufferImageToByteArray(BufferedImage bufferedImage) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", baos); byte[] byteArr = baos.toByteArray(); return byteArr; } } |
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.