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

Posted

技术标签:

【中文标题】使用 struct.unpack_from 解析时,特定图像返回奇怪的值【英文标题】:Specific image returns strange value when parsed with struct.unpack_from 【发布时间】:2021-07-26 20:25:53 【问题描述】:

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

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。有谁知道程序为什么不返回这个值?

【问题讨论】:

【参考方案1】:

从偏移量0x1c 开始的 4 个字节是20 00 03 00,在 little-endian 字节格式中确实是十进制的 196640。问题是你想要的只是20 00,它也是小端字节格式,十进制的 32。

BMP file format 上的 Wikipedia 文章(在 Windows BITMAPINFOHEADER 部分中)说它只是一个两个字节的值 - 所以问题是您解析的字节太多。

解决方法很简单,在struct 格式字符串("&lt;H" 而不是"&lt;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

【讨论】:

以上是关于使用 struct.unpack_from 解析时,特定图像返回奇怪的值的主要内容,如果未能解决你的问题,请参考以下文章

我无法将数据存储为数组

Python 可写缓冲区/内存视图到数组/字节数组/ctypes 字符串缓冲区

perl 将函数解包到 python

将十六进制值的列表/字符串解压缩为整数

解析时动态切换解析器

使用 SAX 解析器解析自关闭 XML 标记时遇到问题