简体   繁体   中英

Java's ImageIO.read() return nulls

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM