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:
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,jpgetc. andbaosas parameters - Get byte array from ByteArrayOutputStream
baosby callingtoByteArray()method.
Here is complete program:
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.