0

So I try to create an image from a byte array, but I can't figure out why the ImageIO.read() method returns a null pointer without any exception.

@Override
public int setParam(byte[] buffer) {
    mFlag = buffer[0];  //TODO
    mX = Convertor.convert2BytesToInt(buffer[1], buffer[2]);
    mY = Convertor.convert2BytesToInt(buffer[3], buffer[4]);    
    mWidth = Convertor.convert2BytesToInt(buffer[5], buffer[6]);
    mHeight = Convertor.convert2BytesToInt(buffer[7], buffer[8]);
    mLength = Convertor.convert4BytesToInt(buffer[9], buffer[10], buffer[11], buffer[12]);

    byte[] bufferpix = Arrays.copyOfRange(buffer, 13, 13+mLength);
    ByteArrayInputStream in = new ByteArrayInputStream(bufferpix);
    try {
        mImage = ImageIO.read(in);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 13+mLength;
}

@Override
public void draw(Graphics2D g, ArrayList<Color> palette) {
    System.out.print("Draw Image\n");
    g.drawImage(mImage, mX, mY, mWidth, mHeight, null);
}

The buffer seems to be okay, it contains data RGBA (1 byte for each, so 4 bytes per pixels). Do you see any problem with that usage? Thx

Btw, if you wonder, this buffer has previously been created by the Android class Bitmap.

Gyome
  • 1,333
  • 2
  • 15
  • 23
  • 1
    javadoc: If no registered `ImageReader` claims to be able to read the resulting stream, `null` is returned. Check your data, probably it is corrupted – hoaz Dec 24 '12 at 10:09
  • alright, but my buffer is of the right size, the bytes are ordered as I said (RGBA), and for example if I send a block of dark red pixels, I contains a series of {110,0,0,-1} which seems correct to me. Isn't something missing in my code to precise I want to use RGBA? – Gyome Dec 24 '12 at 11:09
  • I am not sure about android, but Java core supports only BMP, GIF, JPEG, PNG and WBMP formats. Also it should contain valid image header – hoaz Dec 24 '12 at 11:29

1 Answers1

0

I wasn't using the right method:

    int[] bufferpix = new int[mLength];
    for(int i=0; i<mLength;i++){
        bufferpix[i] = buffer[i+13];
    }
    mImage = new BufferedImage(mWidth, mHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE);
    mImage.getRaster().setPixels(0, 0, mWidth, mHeight, bufferpix);

This fill my image correctly. Too bad that setPixels can't take a byte array for parameter, which make the conversion uggly (I haven't look for a better way to copy my bytes array in a int array yet, probably there is one).

Gyome
  • 1,333
  • 2
  • 15
  • 23