You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Huffman树图像解码ARGB值异常问题求助

Huffman图像解码时ARGB值异常问题

我基于Huffman算法构建存储ColorCodes的树,encode方法可遍历输入字符串解析为int,匹配ColorCodes颜色值后拼接成新字符串;EncodeGraphic方法遍历图像行结合位操作完成编码。decode方法能通过编码后的二进制字符串遍历二叉树实现解码,但**decodeGraphic方法在移位操作后无法返回正确的ARGB值**。

以下是我的decodeGraphic实现代码:

public void decodeGraphic(String inputFile, String outputFile) throws InvalidHuffmanCodeException, IOException {
    // Fill in this method
    // Create and output file using BufferedReader (i.e., BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) )
    // Note the height and width must be read in from the input file (first two lines)
    // The remaining lines in the input file are the pixels
    // Call the decode method for each line.
    // The returned String must be parsed on the comma to get the A, R, G and B values
    // Combine channels into one "bit" by using the left bit-shiffter, <<, and bitwise or, |
    // Call setRGB to set the pixel
    // When all the pixels are set, use ImageIO's static write method to write the graphic file (.png file)
    //*************************************

    int height, width;
    String a, r, g, b;
    int al, re, gr, bl, x = 0, y = 0;
    Scanner in = new Scanner(new File(inputFile));
    height = Integer.parseInt(in.nextLine());
    width = Integer.parseInt(in.nextLine());
    BufferedImage output = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
    String[] sA;

    while(in.hasNextLine()){
        String temp = decode(in.nextLine());
        sA = temp.split(",");
        a = sA[0];
        r = sA[1];
        g = sA[2];
        b = sA[3];

        al = Integer.parseUnsignedInt(a);
        re = Integer.parseUnsignedInt(r);
        gr = Integer.parseUnsignedInt(g);
        bl = Integer.parseUnsignedInt(b);

        int updatedPixel = (al << 24) | (re << 16) | (gr << 8) | (bl);

        output.setRGB(x % output.getWidth(), y % output.getHeight(), updatedPixel);

        x++;

        if(x % output.getHeight() == 0 && x != 0) {
            y++;
        }
    }

    ImageIO.write(output, "png", new File(outputFile));

    //************************************
}

测试情况

5个decodeGraphic测试仅通过2个,其中一个失败案例如下:

预期输出:
255,37,21,19
255,45,30,27
255,43,28,26
255,45,28,24
255,43,26,21
255,43,24,17
255,49,30,22
255,48,27,24

实际输出:
255,100,100,100
255,113,115,117
255,144,145,147
255,89,91,93
255,91,93,95
255,98,98,98
255,92,92,92
255,100,100,100

内容的提问来源于stack exchange,提问作者Robbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:55:42