2

I am trying to convert a byte array of length 128 to a 32x32 bitmap stored in a BufferedImage. I am using the following code:

private BufferedImage fSP;

public Pattern( byte[] aBitData ) {
  if ( aBitData == null ) {
    throw new IllegalArgumentException( "Please provide a non-null byte array of length 128: " + aBitData );
  }
  else if ( aBitData.length != 128 ) {
    throw new IllegalArgumentException( "Please provide a non-null byte array of length 128: " + aBitData.length );
  }
  InputStream in = new ByteArrayInputStream( aBitData );
  try {
    fSP = ImageIO.read( in );
  } catch( IOException e ) {
    e.printStackTrace();
  }
}

But every time fSP is set to null for some reason. I don't understand why this happens. Could anyone help me out?

ChrisV
  • 133
  • 2
  • 9

3 Answers3

1

From the JavaDoc:

Returns a BufferedImage as the result of decoding a supplied InputStream with an ImageReader chosen automatically from among those currently registered. The InputStream is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.

Looks as if the byte array's contents can't be decoded as a known image format.

G_H
  • 11,739
  • 3
  • 38
  • 82
0

there could be another reason of getting null, if you modified aBitData such way that doesn't represent any image, suppose - if you modify first byte, which is image header byte, not image data.

0

I suspect that the data provided in your bit array does not correspond to any supported file format, i.e. can be read by any of the implemented ImageReaders.

Howard
  • 38,639
  • 9
  • 64
  • 83
  • This is indeed probably the case, how would I go about fixing this problem? The data is provided as a byte array with a length of 128, where each bit represents one pixel (black/white). Do I have to make my own ImageReader, or are there perhaps other ways of converting such a byte array into a BufferedImage? – ChrisV Oct 31 '11 at 10:23
  • @ChrisV You may directly instanciate a `BufferedImage` of type `TYPE_BYTE_BINARY` and set the bit data directly. – Howard Oct 31 '11 at 10:25