Java Program to Convert Byte Array to Image
A byte array is the array of bytes that is used to store the collection of binary data. For example, the byte array of an image stores the information of every pixel of the image. In the byte array, we can store the content of any file in binary format. We can initialize the byte array with the bytes as we initialize the normal array.
In this article, we are going to learn to convert the byte array to an image in Java.
Converting Byte Array to Image:
If we have given information of every byte of the image in the array format, we can derive the image from that array. We can write and read the image details using the ImageIO class in Java. We will use the below methods of the ImageIO class to convert the byte array into the image.
- toByteArray(): To convert the image to byte array.
- ByteArrayInputStream( byteArray ): To create object of the ByteArrayInputStream class.
- ImageIO.read(): To read the image by passing the ByteArrayInputStream class object as a parameter.
- ImageIO.write(): To write the image.
1. Here, we need the byte array to convert it into the image. So, we first read the image file and create the byte array for that image.
Read the image file using the read() method of Image.IO class.
BufferedImage image = ImageIO.read(new File("Image path"));
Create the object of the ByteArrayOutputStream class and write the image into that which we have read in the above step.
ByteArrayOutputStream outStreamObj = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", outStreamObj);
Convert the image into the byte array.
byte  byteArray = outStreamObj.toByteArray();
2. Now, read the byte array and generate a new image file.
Create the object of the ByteArrayInputStream class to read the byte array.
ByteArrayInputStream inStreambj = new ByteArrayInputStream(byteArray);
Read the image from the object of the ByteArrayInputStream class.
BufferedImage newImage = ImageIO.read(inStreambj);
Create a new file and write an image into that which we have read from the byte array.
ImageIO.write(newImage, "jpg", new File("outputImage.jpg") );