How to find file extension of base64 encoded image in Python

浪子不回头ぞ 提交于 2019-12-04 05:01:18

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.

I have Written code in Lambda which will find the type of an image and also checks base64 is image or not.

The following code will sure help someone.

import base64
import imghdr
def lambda_handler(event, context):
    image_data = event['img64']    # crate "json event" in lambda 
                                   # Sample JSON Event ========>  { "img64" : BASE64 of an Image }
                                   # Get BASE64 Data of image in image_data variable.
    sample = base64.b64decode(image_data)      # Decode the base64 data and assing to sample.

    for tf in imghdr.tests:
        res = tf(sample, None)
        if res:
            break;
    print("Extension OR Type of the Image =====>",res)
    if(res==None): # if res is None then BASE64 is of not an image.
            return {
            'status': 'False',
           'statusCode': 400,
           'message': 'It is not image, Only images allowed'
          }
    else:
        return 'It is image'  

Note :- The Above code is written Lambda (AWS) in python, You can copy and paste the following code to your local machine and test it as follows.

import base64
import imghdr
image_data = "BASE64 OF AN IMAGE"
sample = base64.b64decode(image_data)      # Decode the base64 data and     assing to sample.

for tf in imghdr.tests:
    res = tf(sample, None)
    if res:
        break;
print("Extension OR Type of the Image =====>",res)
if(res==None):
    print('It is not image, Only images allowed')
else:
    print('It is image')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!