How to Convert An Image To Binary Data In Java

In this instructional exercise, we will learn about how to convert any image to its binary data through the java code.
A parallel picture is a computerized picture that has just two potential qualities for every pixel. Parallel pictures are likewise called bi-level or two-level. This implies every pixel is put away as a solitary piece—i.e., a 0 or 1.

Convert An Image To Binary Data In Java

If you don’t know how to convert an image to its binary data then you are at the right place for your problem’s solution.
We can easily convert any image into binary data by writing simple code.

At first, you have to import these packages to your code and the packages are:-

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import javax.imageio.ImageIO;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

The below code will help you to achieve your goal to convert an image to its respective binary data:-

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import javax.imageio.ImageIO;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class Imagetobinary
 {
 public static void main(String args[]) {
   try {
     System.out.println("superman");
     BufferedImage sourceimage = ImageIO.read(new File("carimage.png"));
     ByteArrayOutputStream bytes = new ByteArrayOutputStream();
     ImageIO.write(sourceimage, "png", bytes);
     String resultantimage = Base64.encode(bytes.toByteArray());
     System.out.println(resultantimage);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
}

You can see we have used Base64 encoding here.

The output of the following result will be:-

superman
11111111111111111111111111
11111100111111111100111111
11110001111100111110001111
11000001111000011110000011
10000000111000011100000001
10000000000000000000000001
00000000000000000000000000
00000000000000000000000000
10000000000000000000000001
10000110001000010001100001
11001111111100111111110011
11100111111100111111100111
11111111111111111111111111

Hope you have understood how we did the conversion of an image to binary data in Java.

Feel free to put your comment down below in the comment section.

Also, read some other tutorials on Java:

Leave a Reply

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