【问题标题】:Python3 - parsing jpeg dimension infoPython3 - 解析 jpeg 维度信息
【发布时间】:2011-08-16 15:13:24
【问题描述】:

我正在尝试编写一个 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 之后),其次我需要避免从嵌入的缩略图中获取数据。有什么建议吗?

【问题讨论】:

    标签: python binary python-3.x hex jpeg


    【解决方案1】:

    此函数的 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
    

    【讨论】:

    • 谢谢,这看起来真的很有用,当然使用struct.unpack('&gt;HH',hex)) 开始会更整洁。
    【解决方案2】:

    由于字节和字符串的更改,我无法在 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()
    

    【讨论】:

    • 您打开了“dafile”,但没有关闭它。除此之外,它工作正常。
    【解决方案3】:

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

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

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

    【讨论】:

    • 据我所知,PIL 仍然无法在 py3k 上运行。
    • 在这种情况下使用pillow
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2016-03-27
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多