How to find file extension of base64 encoded image in Python

Assume having base64 encoded in variable encoded_string, below code works for me:

from base64 import b64decode
import imghdr

encoded_string = 'image base64 encoded'

decoded_string = b64decode(encoded_string)
extension = imghdr.what(None, h=decoded_string)

It is best practices to examine the file's contents rather than rely on something external to the file. Many emails attacks, for example, rely on mis-identifying the mime type so that an unsuspecting computer executes a file that it shouldn't. Fortunately, most image file extensions can be determined by looking at the first few bytes (after decoding the base64). Best practices, though, might be to use file magic which can be accessed via a python packages such as this one or this one.

Most image file extensions are obvious from the mimetype. For gif, pxc, png, tiff, and jpeg, the file extension is just whatever follows the 'image/' part of the mime type. To handle the obscure types also, python does provide a standard package:

>>> from mimetypes import guess_extension
>>> guess_extension('image/x-corelphotopaint')
'.cpt'
>>> guess_extension('image/png')
'.png'

It looks like mimetypes stdlib module supports data urls even in Python 2:

>>> from mimetypes import guess_extension, guess_type
>>> guess_extension(guess_type("data:image/png;base64,")[0])
'.png'

You can use the mimetypes module - http://docs.python.org/2/library/mimetypes.html

Basically mimetypes.guess_extension(mine) should do the job.