Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive a Base64 encoded image in Django Rest Framework and save into ImageField

Tags:

I need to receive an image from an app, and the best way I can think of is to send it into a JSON array encoded in Base64. The image is very small so I don't care about the extra overhead.

I have a model :

class Observation(models.Model):    
    ...
    sonogram_image = models.ImageField(upload_to=sonogram_dir)

And its serialiser:

class ObsvSerializerNoDetect(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Observation

Where should I put the code to decode the image?

like image 668
gozzilli Avatar asked May 13 '13 13:05

gozzilli


People also ask

How do I save a Base64 string image in Django?

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. Make sure you have pip installed. If you're using Linux or Mac OS, then you might have to use pip3 instead of pip .


1 Answers

Here is how you can handle a Base64 encoded image file in a post request at the Django-based (drf also) API end which saves it as an ImageField.

Let say you have a Model as follows:

Class MyImageModel(models.Model):
      image = models.ImageField(upload_to = 'geo_entity_pic')
      data=model.CharField()

So the Corresponding Serializer would be as follows:

 from drf_extra_fields.fields import Base64ImageField

 Class MyImageModelSerializer(serializers.ModelSerializers):
      image=Base64ImageField() # From DRF Extra Fields
      class Meta:
         model=MyImageModel
         fields= ('data','image')
      def create(self, validated_data):
        image=validated_data.pop('image')
        data=validated_data.pop('data')
       return MyImageModel.objects.create(data=data,image=image)

The corresponding View can be as follows:

elif request.method == 'POST':
    serializer = MyImageModelSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=201)
    return Response(serializer.errors, status=400)

Notice In the Serializer I have used Implementation of Base64ImageField provided in the module django-extra-field

To install this module run the command

pip install django-extra-fields

Import the same and Done!

Send (via post method) your image as an Base64 encoded String in JSON object along with any other data you have.

like image 126
Nikhil Avatar answered Sep 19 '22 16:09

Nikhil