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

3

5

I want to read an image from a url and convert it into binary data. Please help me..

        byte[] data = null;
        ByteArrayOutputStream bas = null;
        try {
            URL u = new URL(
                    "http://www.eso.org/public/archives/images/screen/eso0844a.jpg");
            HttpURLConnection con1 = (HttpURLConnection) u.openConnection();
            con1.setAllowUserInteraction(true);
            con1.setRequestMethod("GET");
            con1.connect();
            InputStream is = con1.getInputStream();
            BufferedImage imgToServe = null;
            if (is != null) {
                imgToServe = ImageIO.read(is);
            }
            bas = new ByteArrayOutputStream();
            ImageIO.write(imgToServe, "jpg", bas);

            File f = new File("C:\\img.jpg");
            ImageIO.write(imgToServe, "jpg", f);

            data = bas.toByteArray();
            String str = "";
            for (int i = 0; i < data.length; i++) {
                str = str + toBinary(data[i]);
            }
            System.out.println(str);

        } catch (HTTPException he) {

        } catch (IOException ioe) {
        }
    }

    private static String toBinary(byte b) {
        StringBuilder sb = new StringBuilder("00000000");

        for (int bit = 0; bit < 8; bit++) {
            if (((b >> bit) & 1) > 0) {
                sb.setCharAt(7 - bit, '1');
            }
        }
        return (sb.toString());
    }
Buller answered 14/2, 2011 at 7:1 Comment(2)
Which format do you want? Jpg, gif,... etcFanya
@Fanya : jpg. Thanks for your responseBuller
P
8

If you're reading the image from a URL, it will already be in a binary format. Just download the data and ignore the fact that it's an image. The code which is involved in download it won't care, after all. Assuming you want to write it to a file or something similar, just open the URLConnection and open the FileOutputStream, and repeatedly read from the input stream from the web, writing the data you've read to the output stream.

If that's not what you were after, please clarify the question.

EDIT: If you really want to get the data as individual bits (which seems somewhat odd to me) you should separate the problem in two:

  • Downloading the data (see above; if you don't need it on disk, consider writing to a ByteArrayOutputStream)
  • Converting arbitrary binary data (a byte array or an input stream) into 0s and 1s

How you tackle the latter task will depend on what you actually want to do with the bits. What's the real aim here?

Pickerelweed answered 14/2, 2011 at 7:3 Comment(5)
I want to send this image in binary format to another site for some other process.Buller
@Sarika: Then you almost certainly don't want to decompose it into arbitrary bits. Either just download it into memory or to a file. Ignore the fact that it's an image - it's just a blob of data as far as you need to care. I suspect you're being mislead by the word "binary" in the description of the other site. If they say, "you can upload binary data" or something like that, they're not asking you to decompose it into 0s and 1s as text. It just means it's arbitrary data.Pickerelweed
Hi I add my code with my question. I tried to convert the byte array into binary data. But where did I mistake? It process as infinite loop. Please correct me.Buller
My problem is in converting arbitrary binary data (a byte array or an input stream) into 0s and 1s. Thank youBuller
@Sarika: But why do you think you need to convert it into 0s and 1s? Why on earth would the other site require that?Pickerelweed
F
5

You can use the standard ImageIO for this. The read method takes a URL and retrieves it to an Image. Then you can use the write method to write it to a File or like in this case a ByteArrayOutputStream which outputs the image to a in-memory buffer.

public static void main(String[] args) throws Exception {

    // read "any" type of image (in this case a png file)
    BufferedImage image = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));

    // write it to byte array in-memory (jpg format)
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    ImageIO.write(image, "jpg", b);

    // do whatever with the array...
    byte[] jpgByteArray = b.toByteArray();

    // convert it to a String with 0s and 1s        
    StringBuilder sb = new StringBuilder();
    for (byte by : jpgByteArray)
        sb.append(Integer.toBinaryString(by & 0xFF));

    System.out.println(sb.toString());
}
Fanya answered 14/2, 2011 at 7:15 Comment(5)
Is it a byte array? I need it as 0s and 1sBuller
@Sarika: What makes you think you need it as 0s and 1s? You would never upload it to another site as a string of 1s and 0s. I suspect you're misunderstanding the documentation of whatever you're trying to do with it next.Pickerelweed
@Sarika: Each byte in the jpgByteArray is actually eight "0s and 1s".Fanya
Hi I add my code with my question. I tried to convert the byte array into binary data. But where did I mistake? It process as infinite loop. Please correct me.Buller
@Sarika: Why do you want to convert it to a String with the characters 0s and 1s? It does not make sense? This conversion will take time as the image you are downloading is rather big. I think that is why you think it process it in an infinite loop. I edited the answer with a prettier solution but I really do think you are doing it wrong..Fanya
P
4

Load the image from path/url into BufferedImage

public static Raster loadImageRaster(String file_path) throws IOException 
{
    File input = new File(file_path);
    BufferedImage buf_image = ImageIO.read(input);

    buf_image = binarizeImage(buf_image);

    return buf_image.getData(); //return raster
}

Make a Binary Type BufferedImage from the original BufferedImage

public static BufferedImage binarizeImage(BufferedImage img_param) 
{
    BufferedImage image = new BufferedImage(
        img_param.getWidth(), 
        img_param.getHeight(),                                    
        BufferedImage.TYPE_BYTE_BINARY
    );

    Graphics g = image.getGraphics();
    g.drawImage(img_param, 0, 0, null);
    g.dispose();

    return image;
}

Convert the BufferedImage to Raster so that you can manipulate it pixel by pixel

imageRaster.getSample(x, y, 0)

Raster.getSample(x,y, channel) will return 0s or 1s.

channel = 0 for TYPE_BYTE_BINARY images

Pyosis answered 24/10, 2015 at 12:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.