简体   繁体   English

Java的ImageIO.read()返回null

[英]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. 因此,我尝试从字节数组创建图像,但是我无法弄清楚为什么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). 缓冲区似乎还可以,它包含数据RGBA(每个1字节,因此每个像素4字节)。 Do you see any problem with that usage? 您觉得这种用法有问题吗? Thx 谢谢

Btw, if you wonder, this buffer has previously been created by the Android class Bitmap. 顺便说一句,如果您想知道,此缓冲区以前是由Android类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). 太糟糕了,setPixels不能将字节数组用作参数,这使转换变得很困难(我还没有找到一种更好的方法将字节数组复制到int数组中,也许有一种方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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