How can I guess an image's mime type, in a cross-platform manner, and without any external libraries?
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.
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.
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.
If you know in advance that you only need to handle a limited number of file formats you can use the imghdr.what function.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With