Reading Image Sizes

An example of reading the bounds of an image without using external applications. This is more fast than that, and is useful when you've read a lot of images in jpg, png or gif format. So, the above image is calculated 500x33 pixels.

def get_image_size(fname):
    """ return the image sizes """

    myext = os.path.splitext(fname)[1]

    with open(fname, "rb") as fhandle:
        head = fhandle.read(24)
        if len(head) != 24:
            return [1, 1]
        if myext == ".png":
            check = struct.unpack(">i", head[4:8])[0]
            if check != 0x0d0a1a0a:
                return
            width, height = struct.unpack('>ii', head[16:24])
        elif myext == ".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))
            except Exception:   
                return [1, 1]
        else:
            return [1, 1]

        return [width, height]