How to convert Byte Array to Image in java with easy example

By Saruque Ahamed Mollick

This is a Java tutorial on how to convert Byte array to image in Java. In my previous Java tutorial, I have shown you How to convert an image to byte array in Java
So I am again with this new tutorial. This time you will be given a Byte array and you will have to convert it to an Image using Java.

Java has its own ImageIO class so that we can read and write images in Java. In order to convert a byte array to an image we need to follow these following steps:

  • Create a ByteArrayInputStream object.
  • Read the image. ( using the read() method of the ImageIO class )
  • Finally, Write the image. ( using the write() method of the ImageIO class )

Convert Byte Array to Image in Java

Take a look at the following example:



import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class Codespeedy {
   public static void main(String[] args) throws Exception {
      BufferedImage buffered_image= ImageIO.read(new File("myfile.jpg"));
      ByteArrayOutputStream output_stream= new ByteArrayOutputStream();
      ImageIO.write(buffered_image, "jpg", output_stream);
      byte [] byte_array = output_stream.toByteArray();
      ByteArrayInputStream input_stream= new ByteArrayInputStream(byte_array);
      BufferedImage final_buffered_image = ImageIO.read(input_stream);
      ImageIO.write(final_buffered_image , "jpg", new File("final_file.jpg") );
      System.out.println("Converted Successfully!");
   }
}

If everything goes fine, the output will be like this:

Converted Successfully!

Methods and classes:

ImageIO.write() – This method writes an image file.

ByteArrayOutputStream – This class holds a copy of data so that it can forward it later to multiple streams easily.

ByteArrayInputStream –  read the reference https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html

Also read, Guess The Number Game Using Java with Source Code

Leave a Reply

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