如何使用标准Python类获取图像大小(不使用外部库)? [英] How to obtain image size using standard Python class (without using external library)?

查看:534
本文介绍了如何使用标准Python类获取图像大小(不使用外部库)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Python 2.5. And using the standard classes from Python, I want to determine the image size of a file.

我听说过PIL(Python图像库),但需要安装到

I've heard PIL (Python Image Library), but it requires installation to work.

如果不使用任何外部库,只需使用Python 2.5自己的模块,我如何获得图像的大小?

How might I obtain an image's size without using any external library, just using Python 2.5's own modules?

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

Note I want to support common image formats, particularly JPG and PNG.

推荐答案

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

Here's a python 3 script that returns a tuple containing an image height and width for .png, .gif and .jpeg without using any external libraries (ie what Kurt McKee referenced above). Should be relatively easy to transfer it to 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类获取图像大小(不使用外部库)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆