Java的ImageIO.read()返回null

时间:2021-12-07 21:20:28

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.

所以我尝试从字节数组创建一个图像,但我无法弄清楚为什么ImageIO.read()方法返回一个没有任何异常的空指针。

@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

缓冲区似乎没问题,它包含数据RGBA(每个1个字节,每个像素4个字节)。你觉得这个用法有什么问题吗?谢谢

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

顺便说一下,如果你想知道,这个缓冲区以前是由Android类Bitmap创建的。

1 个解决方案

#1


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

这正确填写我的图像。太糟糕了,setPixels不能为参数取一个字节数组,这使得转换成为uggly(我还没有找到一种更好的方法来复制我在int数组中的字节数组,可能还有一个)。

#1


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

这正确填写我的图像。太糟糕了,setPixels不能为参数取一个字节数组,这使得转换成为uggly(我还没有找到一种更好的方法来复制我在int数组中的字节数组,可能还有一个)。