'How to convert binary image to binary array in java?

I have a binary image like this:

enter image description here

I want to represent or convert this image or (any binary image) in binary array of 0's and 1's then print its values (of course it should be 0's and 1's).

My code prints non-binary values:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class PP {

    public static void main(String argv[]) throws IOException
    {
        File file = new File("binary.jpg");
        BufferedImage originalImage = ImageIO.read(file);
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        ImageIO.write(originalImage, "jpg", baos);
        byte[] imageInByte = baos.toByteArray();

        for(int i = 0; i < imageInByte.length; i++)
        {
            System.out.println(imageInByte[i]);
        }
    }
}


Solution 1:[1]

Maybe i didn't found the optimal answer for my question but these links help me so i accept this as an answer for my question.

Convert an image to binary data (0s and 1s) in java

How to convert a byte to its binary string representation

Edit

I worked more and finally found a way to represent each bit of the binary image in a single line:

here is the code:

StringBuilder check = new StringBuilder();
for(int i = 0; i < imageInByte.length; i++)
{
    check.append(Integer.toBinaryString(imageInByte[i]));
}

String array[] = check.toString().split("");

for(int i = 0; i < array.length; i++){
    System.out.println(array[i)];
}

Solution 2:[2]

This code converts an image to a String that contains 0 for white and 1 for black pixels. The result is not an 2 dimensional array but just one long String with 0/1 values.

    public static String getBinaryImage(BufferedImage image) {
    StringBuffer result = new StringBuffer();
    int width = image.getWidth();
    int height = image.getHeight();
    for (int i = 0; i < height; i++)
        for (int j = 0; j < width; j++)
            result.append(image.getRGB(j, i) == -1 ? 0 : 1);
    return result.toString();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2