import struct import imghdr def getImageSize(fname): with open(fname, 'rb') as fhandle: head = fhandle.read(24) if len(head) != 24: raise RuntimeError("Invalid Header") if imghdr.what(fname) == 'png': check = struct.unpack('>i', head[4:8])[0] if check != 0x0d0a1a0a: raise RuntimeError("PNG: Invalid check") width, height = struct.unpack('>ii', head[16:24]) elif imghdr.what(fname) == 'gif': width, height = 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)) else: raise RuntimeError("Unsupported format") return width, height