Getting the Image Size from Common File Formats


A short Python function to retrieve image file dimensions, taken from Draco via this ticket on the Django site:

def _imageInfo(fhandle):
    """
    Determine the image type of fhandle and return its size.
    from draco
    """

    head = fhandle.read(24)
    if len(head) != 24:
        return
    if head[:4] == '\x89PNG':
        # PNG
        check = struct.unpack('>i', head[4:8])[0]
        if check != 0x0d0a1a0a:
            return
        width, height = struct.unpack('>ii', head[16:24])
        img_type = 'PNG'
    elif head[:6] in ('GIF87a', 'GIF89a'):
        # GIF
        width, height = struct.unpack('<HH', head[6:10])
        img_type = 'GIF'
    elif head[:4] == '\xff\xd8\xff\xe0' and head[6:10] == 'JFIF':
        # JPEG
        img_type = '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 img_type, width, height

See Also: