How to obtain image size using standard Python class (without using external library)? How to obtain image size using standard Python class (without using external library)? python python

How to obtain image size using standard Python class (without using external library)?


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 structimport imghdrdef 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


Kurts answer needed to be slightly modified to work for me.

First, on ubuntu: sudo apt-get install python-imaging

Then:

from PIL import Imageim=Image.open(filepath)im.size # (width,height) tuple

Check out the handbook for more info.


Here's a way to get dimensions of a png file without needing a third-party module. From http://coreygoldberg.blogspot.com/2013/01/python-verify-png-file-and-get-image.html

import structdef get_image_info(data):    if is_png(data):        w, h = struct.unpack('>LL', data[16:24])        width = int(w)        height = int(h)    else:        raise Exception('not a png image')    return width, heightdef is_png(data):    return (data[:8] == '\211PNG\r\n\032\n'and (data[12:16] == 'IHDR'))if __name__ == '__main__':    with open('foo.png', 'rb') as f:        data = f.read()    print is_png(data)    print get_image_info(data)

When you run this, it will return:

True(x, y)

And another example that includes handling of JPEGs as well:http://markasread.net/post/17551554979/get-image-size-info-using-pure-python-code