Zlib 压缩 header 校验和失败,错误为 -3

Zlib compression header fails checksum with error -3

我正在尝试使用 Fixed Huffman 在 python 中编写自己的 deflate 实现。当我将图像打包回 .png 文件时,常规图像查看器中没有显示任何内容。每个块 header 都是根据 RFC-1950 的规范形成的。 我已经使用 pngcheck 找出图像没有显示任何内容的原因,并收到了这两条消息:

zlib: compression header fails checksum

zlib: inflate_error = -3

对于 Adler32 值,我计算得像 zlib.adler32(bytearray(scanline))。另一件让我困惑的事情是压缩流的字节顺序,我不完全确定如何将固定的霍夫曼代码位打包在字节中,我知道它在 RFC-1951 中指定。

#zLibHeaderArray = bytearray([CMF,FLG])
zLibHeaderArray = bytearray([78,1])
outputPNG.write(zLibHeaderArray)

#First three bits per block
outputBitStream = ba.bitarray(endian = 'big')

if(isLast != 1):
    outputBitStream += ba.bitarray('001')
else:
    outputBitStream += ba.bitarray('101')

#-- here i transform the input scanline with lz77 and huffman and load it into the big endian bitarray

outputBitStream += ba.bitarray(getHuffman(256,huffman))
outputBitStream.tofile(outputPNG)
#Adler32 Checksum

adler32Value = zlib.adler32(bytearray(scanline))
a1, a2, a3, a4 = (adler32Value & 0xFFFFFFFF).to_bytes(4, 'big')

adler32Array = bytearray([a1,a2,a3,a4])
outputPNG.write(adler32Array)

CRC 不会导致 iDAT 块出错,所以我最好的猜测是 Adler32 校验和。

您应该仔细阅读错误信息。 "compression header fails checksum" 表示错误的是 zlib header,而不是 Adler-32 的预告片。 two-byte header 包含一个 five-bit 检查值,该值未在您的流中正确设置。 (或者您可能完全忘记了 header。)