How to convert image to byte array in Java

By Saruque Ahamed Mollick

This is a Java tutorial on how to convert an image to byte array in Java. It sounds cool, right? You will be given an image and you have to convert image to byte array in Java.



Thanks to Java for providing some useful classes to work with images in Java. Otherwise, our java program would be much more bigger. So, we gonna use those classes to make our program easier and cleaner.

Here we will use some Java inbuild methods and classes. Let’s take a look at these methods and classes

  • read() method
  • ByteArrayOutputStream class
  • write() method of ImageIO class
  • toByteArray() method

Don’t panic if you are not familiar with these methods and classes. I will explain later.

Guess The Number Game Using Java with Source Code

Convert image to byte array in Java

Algorithm:

  1. Apply read() method the ImageIO class to read the image file.
  2. Create an object of ByteArrayOutputStream class.
  3. Use write() method to the created object.
  4. Now, convert the contents to the byte array using toByteArray() method.

Java Program to convert an image to byte array

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

public class ByteArrayConversion {
   public static void main(String[] args) throws Exception {
      BufferedImage bufferimage = ImageIO.read(new File("myimage.jpg"));
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      ImageIO.write(bufferimage, "jpg", output );
      byte [] data = output.toByteArray();
   }
}

Now to check if the Byte array data is working or not Just encode it in base64.

String base64 = Base64.encode(data);
System.out.println(base64);

Just use the printed value in your image src tag to check if the encoding is working or not.

How To Add text to image in PHP – Watermarking

Methods and classes:

ImageIO.read() – This method reads an image file.

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

Free cool 3d image hover effect source code download

3D Photo/Image Gallery (on space) Using HTML5 CSS JS

Leave a Reply

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