Skip to content

Instantly share code, notes, and snippets.

@IamMiracleAlex
Created February 27, 2023 12:26
Show Gist options
  • Save IamMiracleAlex/59266bfc2fc835a368a980930072585b to your computer and use it in GitHub Desktop.
Save IamMiracleAlex/59266bfc2fc835a368a980930072585b to your computer and use it in GitHub Desktop.
Convert an image to base64 string and convert base64 string to a django image
import base64
from django.core.files.uploadedfile import SimpleUploadedFile
def image_to_base64(image) -> str:
"""Converts image to base64 string"""
return base64.b64encode(image.read()).decode()
def convert_str_to_image(image_data: str):
"""Converts base 64 string to django image"""
decoded_data = base64.b64decode(image_data.encode())
myfile = SimpleUploadedFile.from_dict(
{
"filename": "logo",
"content": decoded_data,
"content-type": "'image/jpeg'",
}
)
return myfile
###################### USAGE ######################
# 1. This can be used to pass image data into celery
# 2. Can be used to store image data as base64
# 3. Can be used to transfer image data with json as base64
# 4. Can be used to convert base64 image data to image file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment