Python3 - 解析jpeg尺寸信息

Tir*_*ove 5 python binary hex jpeg python-3.x

我正在尝试编写一个 python 函数来解析 jpeg 文件的宽度和高度。我目前的代码看起来像这样

import struct

image = open('images/image.jpg','rb')
image.seek(199)
#reverse hex to deal with endianness...
hex = image.read(2)[::-1]+image.read(2)[::-1]
print(struct.unpack('HH',hex))
image.close()
Run Code Online (Sandbox Code Playgroud)

不过,这有几个问题,首先我需要浏览文件以找出从哪里读取(在 ff c0 00 11 08 之后),其次我需要避免从嵌入的缩略图中获取数据。有什么建议么?

Aco*_*orn 3

此函数的 JPEG 部分可能有用:http://code.google.com/p/bfg-pages/source/browse/trunk/pages/getimageinfo.py

jpeg.read(2)
b = jpeg.read(1)
try:
    while (b and ord(b) != 0xDA):
        while (ord(b) != 0xFF): b = jpeg.read(1)
        while (ord(b) == 0xFF): b = jpeg.read(1)
        if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
            jpeg.read(3)
            h, w = struct.unpack(">HH", jpeg.read(4))
            break
        else:
            jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
        b = jpeg.read(1)
    width = int(w)
    height = int(h)
except struct.error:
    pass
except ValueError:
    pass
Run Code Online (Sandbox Code Playgroud)