Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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());
    }
like image 911
Sarika.S Avatar asked Feb 14 '11 07:02

Sarika.S


2 Answers

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?

like image 83
Jon Skeet Avatar answered Sep 27 '22 22:09

Jon Skeet


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());
}
like image 40
dacwe Avatar answered Sep 27 '22 21:09

dacwe