python - 如何使用标准 Python 类(不使用外部库)获取图像大小?

标签 python image python-2.5

我正在使用 Python 2.5。并使用 Python 中的标准类,我想确定文件的图像大小。

我听说过 PIL(Python 图像库),但它需要安装才能工作。

我如何在不使用任何外部库的情况下仅使用 Python 2.5 自己的模块来获取图像的大小?

注意我想支持常见的图像格式,尤其是 JPG 和 PNG。

最佳答案

这是一个 python 3 脚本,它返回一个元组,其中包含 .png、.gif 和 .jpeg 的图像高度和宽度,而不使用任何外部库(即上面提到的 Kurt McKee)。将其转移到 Python 2 应该相对容易。

import struct
import imghdr

def get_image_size(fname):
    '''Determine the image type of fhandle and return its size.
    from draco'''
    with open(fname, 'rb') as fhandle:
        head = fhandle.read(24)
        if len(head) != 24:
            return
        if imghdr.what(fname) == 'png':
            check = struct.unpack('>i', head[4:8])[0]
            if check != 0x0d0a1a0a:
                return
            width, height = struct.unpack('>ii', head[16:24])
        elif imghdr.what(fname) == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        elif imghdr.what(fname) == 'jpeg':
            try:
                fhandle.seek(0) # Read 0xff next
                size = 2
                ftype = 0
                while not 0xc0 <= ftype <= 0xcf:
                    fhandle.seek(size, 1)
                    byte = fhandle.read(1)
                    while ord(byte) == 0xff:
                        byte = fhandle.read(1)
                    ftype = ord(byte)
                    size = struct.unpack('>H', fhandle.read(2))[0] - 2
                # We are at a SOFn block
                fhandle.seek(1, 1)  # Skip `precision' byte.
                height, width = struct.unpack('>HH', fhandle.read(4))
            except Exception: #IGNORE:W0703
                return
        else:
            return
        return width, height

关于python - 如何使用标准 Python 类(不使用外部库)获取图像大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8032642/

相关文章:

windows - 使用命令提示符启动已保存的 Python 程序时遇到问题

python——for循环的理解

Python Regex 替换 - 是否可以进行有条件的替换?

python - 如何在 discord py 中创建默认命令?

image - Tensorflow - 洗牌和分割图像和标签的数据集

python - from __future__ import absolute_import 实际上做了什么?

java - 从 Java 调用 Python

python - 是否可以通过 doctest 测试使用 get_type_hints 的函数?

c# - 使用 Emgu 读取图像和将其读取为字节数组之间的区别

android - 具有相同图像资源的 BitmapFactory.decodeStream 和 BitmapFactory.decodeFile 行为