It is best to check the contents of the file rather than relying on something external to the file. For example, many email attacks rely on an incorrect mime identifier, so the unsuspecting computer executes a file that it should not. Fortunately, most image file extensions can be determined by looking at the first few bytes (after base64 decoding). However, it is best to use file magic , which can be accessed through python packages such as this or this .
Most image file extensions are obvious from mimetype. For gif, pxc, png, tiff and jpeg, the file extension is all that follows the "image /" part of the mime type. To handle obscure types, python also provides a standard package:
>>> from mimetypes import guess_extension >>> guess_extension('image/x-corelphotopaint') '.cpt' >>> guess_extension('image/png') '.png'
John1024
source share