Java Graphics How to - How to grab byte[] of an Image in java?








Question

We would like to know how to how to grab byte[] of an Image in java?.

Answer

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
// w w w . j a  va  2s .com
public class Main {
  public static void main(String[] args) throws IOException {
    URL url = new URL("http://www.java2s.com/style/download.png");

    InputStream inputStream = url.openStream();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];

    int n = 0;
    while (-1 != (n = inputStream.read(buffer))) {
      output.write(buffer, 0, n);
    }
    inputStream.close();

    byte[] data = output.toByteArray();

    OutputStream out = new FileOutputStream("data.png");
    out.write(data);
    out.close();

    for (byte b : data) {
      System.out.printf("0x%x ", b);
    }
  }
}

The code above generates the following result.