我正在尝试编写一个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()
但是有一些问题,首先我需要查看文件以找出从哪里读取(在ff c0 00 11 08之后),其次我需要避免从嵌入的缩略图中获取数据.有什么建议?
解决方法:
此功能的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