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.
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.
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')
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'
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