如何解决Python3-解析jpeg尺寸信息
| 我正在尝试编写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
,由于字节和字符串的更改,我无法在Python3中使用任何解决方案。在Acorn的解决方案的基础上,我想到了这一点,它在Python3中适用于我:
import struct
import io
height = -1
width = -1
dafile = open(\'test.jpg\',\'rb\')
jpeg = io.BytesIO(dafile.read())
try:
type_check = jpeg.read(2)
if type_check != b\'\\xff\\xd8\':
print(\"Not a JPG\")
else:
byte = jpeg.read(1)
while byte != b\"\":
while byte != b\'\\xff\': byte = jpeg.read(1)
while byte == b\'\\xff\': byte = jpeg.read(1)
if (byte >= b\'\\xC0\' and byte <= b\'\\xC3\'):
jpeg.read(3)
h,w = struct.unpack(\'>HH\',jpeg.read(4))
break
else:
jpeg.read(int(struct.unpack(\">H\",jpeg.read(2))[0])-2)
byte = jpeg.read(1)
width = int(w)
height = int(h)
print(\"Width: %s,Height: %s\" % (width,height))
finally:
jpeg.close()
,我的建议:使用PIL(Python影像库)。
>>> import Image
>>> img= Image.open(\"test.jpg\")
>>> print img.size
(256,256)
否则,请使用Hachoir,它是一个纯Python库;特别是hachoir-metadata似乎具有您想要的功能)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。