Skip to content

Instantly share code, notes, and snippets.

@yprez
Last active February 19, 2023 12:08
Show Gist options
  • Save yprez/7704036 to your computer and use it in GitHub Desktop.
Save yprez/7704036 to your computer and use it in GitHub Desktop.
Django rest framework - Base64 image field
import base64
from django.core.files.base import ContentFile
from rest_framework import serializers
class Base64ImageField(serializers.ImageField):
def from_native(self, data):
if isinstance(data, basestring) and data.startswith('data:image'):
# base64 encoded image - decode
format, imgstr = data.split(';base64,') # format ~= data:image/X,
ext = format.split('/')[-1] # guess file extension
data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)
return super(Base64ImageField, self).from_native(data)
@jyotman
Copy link

jyotman commented Aug 28, 2015

Hi please explain where do i use this code?

This is my serializers.py
class Image64Serializer(serializers.ModelSerializer):
class Meta:
model = SampleImage64
fields = ('id', 'image64')

This is models.py
class SampleImage64(models.Model):
image64 = models.ImageField(upload_to('images'))

@xtrinch
Copy link

xtrinch commented Mar 4, 2016

And when I want to fetch that file? I get "http://some-ip/api/users/17/Raw%20content"

@rbtsolis
Copy link

Wuau this method is to convert base64 to image, thank you again, you save my day and my life :D

@icorradi
Copy link

@s2krish Thanks man! Your comment was useful for me!

@kevin-brown
Copy link

You can find a more up-to-date (compatible with 3.x) base64 image field in the following Stack Overflow answer.

Django REST Framework upload image: “The submitted data was not a file”

@arshdoda
Copy link

I have made this field optional. I want to pass null value to the field but its showing error

@darkhaan
Copy link

@kevin-brown thanks, man! You save my day!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment