2011-05-01 94 views
3

我想写一个python函数来解析jpeg文件的宽度和高度。我目前拥有的代码看起来像这样Python3 - 解析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后)其次,我需要避免从嵌入的缩略图中获取数据。有什么建议么?这个功能的

回答

4

的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 
+0

谢谢,这看起来真的很有用,当然使用'struct.unpack(“> HH”,十六进制))'是更整洁作为一个开始。 – 2011-05-01 21:57:03

0

我的建议是:使用PIL(该Python Imaging Library)。

>>> import Image 
>>> img= Image.open("test.jpg") 
>>> print img.size 
(256, 256) 

否则,使用Hachoir这是一个纯粹的Python库;特别是hachoir-metadata似乎有你想要的功能)。

+2

据我所知,PIL仍然不能在py3k上运行。 – Daenyth 2011-05-02 01:13:56

+1

在这种情况下使用'pillow' – malat 2015-09-22 12:13:23

2

由于字节和字符串的变化,我无法获得任何解决方案在Python3中工作。在橡果的解决方案的基础上,我想出了这一点,这对我来说在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() 
+0

您打开'dafile'但不关闭它。除此之外它工作正常。 – user136036 2015-10-25 14:16:48