如何解决使用 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]))
当我输入其他测试图像时,它可以正常工作,但是当我专门从 this page 输入小样本图像时,它输出 196640。我已经在 Hex Editor Neo 中查看了该文件,并且该值所选字节的 32。有谁知道为什么程序不返回这个值?
解决方法
从偏移量 0x1c
开始的 4 个字节是 20 00 03 00
,它确实是 196640 的小端字节格式的十进制。问题是你想要的只是 20 00
,它也是小端字节格式,是 32 十进制。
维基百科关于 BMP file format 的文章(在 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。