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

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.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class Codespeedy {
   public static void main(String[] args) throws Exception {
      BufferedImage buffered_image= 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.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

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

Leave a Reply