Convert base64 request data to image file is a very common requirement. There are a lot of libraries to work on image processing. Here we are using Pillow which is very popular module to convert base64 to image. Here are the steps to do this:
- Activate virtual environment
- Install module using pip
pip install Pillow
- Use below code to convert base64 to image file. You can read the code and easily understand what is going on so no need to explain this. You can modify the code for default FILE_UPLOAD_DIR as per your requirement.
import base64 from PIL import Image import io import uuid ''' convert base64/blob to image file and save in FILE_UPLOAD_DIR ''' def blob_to_image_converter(profile_image_blob, FILE_UPLOAD_DIR): if profile_image_blob is not None and len(profile_image_blob) > 0: image = base64.b64decode(str(profile_image_blob)) #set fileName file_name = uuid.uuid4().hex[:50].upper() fileExtension = '.jpeg' file_name += fileExtension image_path = FILE_UPLOAD_DIR + file_name im = Image.open(io.BytesIO(image)) im.save(image_path, 'jpeg') return file_name return ""
- There are many free online resources to create base64 from an image file. To test the code, you can generate a base64 for any file online.