This website collects cookies to deliver better user experience
How to save Base64 encoded image to Django ImageField?
How to save Base64 encoded image to Django ImageField?
I had to create an API that had to accept an image in Base64 encoded format and save it to Django image field, which requires an image file. So today I learned how to do this.
Step 1: B64 to PIL
The first step will be to convert this B64 image to an image file in memory, I will be using Pillow for this. You can install Pillow using this bash command.
$ pip install pillow
Make sure you have pip installed. If you're using Linux or Mac OS, then you might have to use pip3 instead of pip. But I'm using virtual env, so who cares.
after that, write this function.
import base64
import io
from PIL import Image
defdecodeDesignImage(data):try: data = base64.b64decode(data.encode('UTF-8')) buf = io.BytesIO(data) img = Image.open(buf)return img
except:returnNone
This function will return a PIL image if the B64 data is valid, or it will return None.
Step 2: PIL to Django ImageField
After getting the PIL image, wrote a function that will take this PIL image, convert it into a JPEG file buffer and then inserted it to Database instance using InMemoryUploadedFile