Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 913
iTayb Avatar asked Feb 01 '13 11:02

iTayb


People also ask

How would you determine the MIME type of a file?

The MIME type registry associates particular filename extensions and filename patterns, with particular MIME types. If a match for the filename is found, the MIME type associated with the extension or pattern is the MIME type of the file.

What is the MIME type for image?

One of the most important pieces of data, called the MIME type specifies what the body of text describes. For instance, a GIF image is given the MIME type of image/gif, a JPEG image is image/jpg, and postscript is application/postscript.

How do I specify a MIME type?

In the Connections pane, go to the site, application, or directory for which you want to add a MIME type. In the Home pane, double-click MIME Types. In the MIME Types pane, click Add... in the Actions pane. In the Add MIME Type dialog box, add the file name extension and MIME type, and then click OK.


2 Answers

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

like image 57
pafcu Avatar answered Sep 18 '22 06:09

pafcu


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'
like image 31
iTayb Avatar answered Sep 19 '22 06:09

iTayb