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")
        
        img_type = imghdr.what(fname)
        
        if img_type == '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 img_type == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        
        elif img_type == 'jpeg':
            fhandle.seek(0)
            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
            
            fhandle.seek(1, 1)  # Skip `precision' byte.
            height, width = struct.unpack('>HH', fhandle.read(4))
        
        else:
            raise RuntimeError("Unsupported format")
        
        return width, height
