Skip to content Skip to sidebar Skip to footer

How To Guess Image Mime Type?

How can I guess an image's mime type, in a cross-platform manner, and without any external libraries?

Solution 1:

If you know in advance that you only need to handle a limited number of file formats you can use the imghdr.what function.


Solution 2:

I've checked the popular image types' format on wikipedia, and tried to make a signature:

def guess_image_mime_type(f):
    '''
    Function guesses an image mime type.
    Supported filetypes are JPG, BMP, PNG.
    '''
    with open(f, 'rb') as f:
        data = f.read(11)
    if data[:4] == '\xff\xd8\xff\xe0' and data[6:] == 'JFIF\0':
        return 'image/jpeg'
    elif data[1:4] == "PNG":
        return 'image/png'
    elif data[:2] == "BM":
        return 'image/x-ms-bmp'
    else:
        return 'image/unknown-type'

Solution 3:

If you can rely on the file extension you can use the mimetypes.guess_type function. Note that you may get different results on different platforms, but I would still call it cross-platform.


Post a Comment for "How To Guess Image Mime Type?"