January 28, 2013

Python - verify a PNG file and get image dimensions

useful snippet for getting .png image dimensions without using an external imaging library.

#!/usr/bin/env python

import struct


def 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, height


def 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)

/headnods:
getimageinfo.py source, Portable_Network_Graphics (Wikipedia)

4 comments:

Shawn W. said...

Cool stuff! I assume this is Python 2.x only? It looks like you're assuming byte strings.

Corey Goldberg said...

yup, this is for Python 2.

Andrii said...

Nice snippet. Thanks

Anonymous said...

... (data[:8] == b'\211PNG\r\n\032\n' and (data[12:16] == b'IHDR'))

...
print(is_png(data))
print(get_image_info(data))
...