【问题标题】:Which byte(Alpha, Red, Green, Blue) is wrong when converting byte array with color space of 8BitARGB to BufferedImage.TYPE_4BYTE_ABGR将颜色空间为 8BitARGB 的字节数组转换为 BufferedImage.TYPE_4BYTE_ABGR 时哪个字节(Alpha、Red、Green、Blue)错误
【发布时间】:2015-12-16 17:44:39
【问题描述】:

我已经得到了 8BitARGB 颜色空间中的图像字节数组,需要将这个字节数组转换为 java.awt.BufferedImage。 代码如下:

public void getImage(byte byteArray[]){
        int height = 1920;
        int width = 1080;
        ARGB_to_ABGR(byteArray);
        BufferedImage image1 = new BufferedImage(height, width, 
                BufferedImage.TYPE_4BYTE_ABGR);
        image1.getWritableTile(0, 0).setDataElements(0, 0, height, width, byteArray);
        java.io.File file = new java.io.File("amazing.png");
        try {
            ImageIO.write(image1, "jpg", file);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    
    /*
     * Swap the Red byte and Blue byte
     */
    public void ARGB_to_ABGR(byte byteArray[]){
        int length = byteArray.length;
        byte r = 0;
        byte b = 0;
        for(int i = 0; i < byteArray.length; i++){
            if(length % 4 == 0){
                //do nothing
            }else if(length % 4 == 1){
                r = byteArray[i];
            }else if(length % 4 == 2){
                //do nothing
            }else if(length % 4 == 3){
                b = byteArray[i];
                byteArray[i] = r;
                byteArray[i - 2] = b;
            }
        }
    }

原图如下:

amazing.png 看起来像:

我认为原始字节数组没有任何问题。为了快速调试,仅根据图像效果,谁能告诉哪个字节(Alpha,Red,Green,Blue)是错误的?提前感谢您的帮助。

【问题讨论】:

    标签: java image bufferedimage


    【解决方案1】:

    ARGB_to_ABGR 的代码中,您可能想在现在有length % 4 的地方写i % 4。就目前而言,我猜它什么也没做。

    【讨论】:

    • 谢谢。这实际上是一个愚蠢的错字。但是,修改代码后。图像仍然不是我想要的。也许 8BitARGB 的字节顺序实际上不是 A,R,G,B。我将列举所有可能性。还是谢谢。
    【解决方案2】:

    我认为@Henry 是正确的,因为您的代码中只有一个简单的错字。但是,我想提供另一种编写方式,这种方式(至少对我而言)更易于阅读/理解,因此更不容易出错。

    我相信它也更快,因为它不对索引进行测试。

    此版本一次迭代一个像素(4 个字节)的输入字节数组:

    public void ARGB_to_ABGR(byte[] byteArray) {
        byte tempR = 0;
        for (int i = 0; i < byteArray.length; i += 4) {
            // For each iteration, simply swap R and B
            tempR = byteArray[i + 1];
            byteArray[i + 1] = byteArray[i + 3];
            byteArray[i + 3] = tempR;
        }
    }
    

    【讨论】:

    • 感谢您的帮助。看起来很简洁。
    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 2014-08-08
    相关资源
    最近更新 更多