Convert BufferedImage to Byte Array in Java
In this example we demonstrate how to convert a BufferedImage
to byte[]
using standard Java. We use try-with-resources to manage the closing of OutputStream
.
Convert BufferedImage to Byte Array
We create the BufferedImage
by using ImageIO.read()
and passing in the location of the image as an argument. Since ByteArrayOutputStream
implements Closeable
, we can create a ByteArrayOutputStream
inside the try-catch
block and the java runtime will automatically handle the closing of the stream. Next we write the BufferedImage
to the ByteArrayOutputStream
using ImageIO.write()
. Finally, we return the byte[]
using the ByteArrayOutputStream.toByteArray()
method.
package com.memorynotfound.image;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class BufferedImageToByteArray {
public static void main(String... args){
try {
BufferedImage image = ImageIO.read(new File("/tmp/duke.png"));
byte[] byteArray = toByteArrayAutoClosable(image, "png");
System.out.println("Convert BufferedImage to byte[]: " + Arrays.toString(byteArray));
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] toByteArrayAutoClosable(BufferedImage image, String type) throws IOException {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()){
ImageIO.write(image, type, out);
return out.toByteArray();
}
}
}