特定图像在使用struct.unpack_from解析时返回奇怪的值



我使用以下代码来查找给定图像的位深度:

def parseImage(self):
with open(self.imageAddress, "rb") as image:
data = bytearray(image.read())
bitDepth = struct.unpack_from("<L", data, 0x0000001c)
print("the image's colour depth is " + str(bitDepth[0]))

当我输入其他测试图像时,它可以正常工作,但是当我特别从该页输入小样本图像时,它输出196640。我已经在十六进制编辑器Neo中查看了该文件,所选字节的值为32。有人知道为什么程序不返回这个值吗?

从偏移量0x1c开始的4个字节是20 00 03 00,它实际上是196640十进制的小端字节格式。问题是你想要的是20 00,同样是小端字节格式,32十进制。

维基百科关于BMP文件格式的文章(在Windows BITMAPINFOHEADER中)节)说它只是一个两个字节的值-所以问题是你解析了太多字节。

修复很简单,在struct格式字符串中指定正确的无符号整数字节数("<H"而不是"<L")。注意,我还添加了一些脚手架,以使代码张贴成可运行的东西。

import struct

class Test:
def __init__(self, filename):
self.imageAddress = filename
def parseImage(self):
with open(self.imageAddress, "rb") as image:
data = bytearray(image.read())
bitDepth = struct.unpack_from("<H", data, 0x1c)
print("the image's colour depth is " + str(bitDepth[0]))

t = Test('Small Sample BMP Image File Download.bmp')
t.parseImage()  # -> the image's colour depth is 32

最新更新