Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find file extension of base64 encoded image in Python

I have a base64 encoded image that I decode and save into an ImageField in Django. I want to give the file a random name, but I don't know the file extension.

I have "data:image/png;base64," prepended to the string and I know I could do some regex to extract the mimetype, but I'd like to know if there is a best practices way to go from "data:image/png;base64," to ".png" reliably. I don't want to have my handspun function break when someone suddenly wants to upload a strange image filetype that I don't support.

like image 757
Chris Del Guercio Avatar asked Jan 10 '14 00:01

Chris Del Guercio


People also ask

What file extension is Base64?

Binary file encoded using base64 encoding; often used to convert text data into base64 data; enables more reliable transmission of e-mail attachments and other information; similar to a . MIME attachment.


2 Answers

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')
like image 70
Suraj Kulkarni Avatar answered Oct 04 '22 19:10

Suraj Kulkarni


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'
like image 22
jfs Avatar answered Oct 04 '22 18:10

jfs