How to convert byte array to buffered image

baekacaek picture baekacaek · Nov 16, 2013 · Viewed 11k times · Source

I have a server-side java code that gets a byte array from the client. In order to do some image processing, I need to convert the byte array into a BufferedImage. I have a code that's supposed to do that here:

public void processImage(byte[] data) {
    ByteArrayInputStream stream = new ByteArrayInputStream(data);
    BufferedImage bufferedImage;
    bufferedImage = ImageIO.read(stream);

    // bufferedImage is null
    //...
}

But this doesn't work; bufferedImage is null. According to the ImageIO documentation:

If no registered ImageReader claims to be able to read the resulting stream, null is returned.

How do I tell the ImageReader what image type it is. For instance, if I know the image to be JPEG (which it is, in my case), what am I supposed to do?

EDIT: Thanks for the suggestion that the file is most likely not in JPEG format. This is the client-side code I have that sends the data as String over to the server:

import org.json.JSONObject;

// Client-side code that sends image to server as String
public void sendImage() {
    FileInputStream inputStream = new FileInputStream(new File("myImage.jpg"));
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    while ((bytesRead = inputStream.read(b)) != -1) {
        byteStream.write(b,0,bytesRead);
    }
    byte[] byteArray = byteStream.toByteArray();

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("data",new String(byteArray));

    // ... more code here that sends jsonObject in HTTP post body
}

And this is the server-side code that calls the processImage() function:

// Server-side code that calls processImage() function
public void handleRequest(String jsonData) {
    JSONObject jsonObject = new JSONObject(jsonData);
    processImage(jsonObject.getString("data").getBytes());
}

Answer

Stephen C picture Stephen C · Nov 16, 2013

The most likely explanation is that the byte array doesn't contain a JPEG image. (For instance, if you've just attempted to download it, you may have an HTML document giving an error diagnostic.) If that's the case, you'll need to find what is causing this and fix it.

However, if you "know" that the byte array contains an image with a given format, you could do something like this:

  1. Use ImageIO.getImageReadersByFormatName or ImageIO.getImageReadersByMIMEType to get an Iterator<ImageReader>.
  2. Pull the first ImageReader from the Iterator.
  3. Create an MemoryCacheImageInputStream wrapping a ByteArrayInputStream for the types.
  4. Use ImageReader.setInput to connect the reader to the ImageInputStream.
  5. Use ImageReader.read to get the BufferedImage.