简短回答:(1)“放气”和“32Kb 窗口”是默认设置(2)使用 adler32 而不是 crc32
长答案:
""" PNG 规范要求使用 zlib 的 deflate 方法压缩 IDAT 数据,窗口大小为 32768 字节,但我在 Python zlib 模块中找不到如何设置这些参数。"""
你不需要设置它们。这些是默认值。
如果你真的想为 zlib 指定非默认参数,你可以使用 zlib.compressobj() ...它有几个 Python 文档中没有记录的参数。阅读材料:
来源:Python 的 gzip.py(查看它如何调用 zlib.compressobj)
来源:Python 的 zlibmodule.c(查看其默认值)
SO:这个问题(请参阅 MizardX 和我自己的答案,以及对每个问题的评论)
docs:zlib 网站上的手册
"""至于每个块的 CRC,zlib 模块文档表明它包含一个 CRC 函数。我相信将该 CRC 函数调用为 crc32(data,-1) 将生成我需要的 CRC,尽管如果有必要我可以翻译PNG规范中给出的C代码。"""
请查看zlib 规范 aka RFC 1950 ...它说使用的校验和是adler32
zlib compress 或 compressobj 输出将包含适当的 CRC;为什么你认为你需要自己做?
编辑所以你确实需要一个 CRC-32。好消息:zlib.crc32() 将完成这项工作:
代码:
import zlib
crc_table = None
def make_crc_table():
global crc_table
crc_table = [0] * 256
for n in xrange(256):
c = n
for k in xrange(8):
if c & 1:
c = 0xedb88320L ^ (c >> 1)
else:
c = c >> 1
crc_table[n] = c
make_crc_table()
"""
/* Update a running CRC with the bytes buf[0..len-1]--the CRC
should be initialized to all 1's, and the transmitted value
is the 1's complement of the final running CRC (see the
crc() routine below)). */
"""
def update_crc(crc, buf):
c = crc
for byte in buf:
c = crc_table[int((c ^ ord(byte)) & 0xff)] ^ (c >> 8)
return c
# /* Return the CRC of the bytes buf[0..len-1]. */
def crc(buf):
return update_crc(0xffffffffL, buf) ^ 0xffffffffL
if __name__ == "__main__":
tests = [
"",
"\x00",
"\x01",
"Twas brillig and the slithy toves did gyre and gimble in the wabe",
]
for test in tests:
model = crc(test) & 0xFFFFFFFFL
zlib_result = zlib.crc32(test) & 0xFFFFFFFFL
print (model, zlib_result, model == zlib_result)
Python 2.7 的输出如下。还使用 Python 2.1 到 2.6(含)和 1.5.2 JFTHOI 进行了测试。
(0L, 0L, True)
(3523407757L, 3523407757L, True)
(2768625435L, 2768625435L, True)
(4186783197L, 4186783197L, True)