How to store Image as Binary in Django

Published 28 Nov, 2021

Reading time: 2 Mins


Sometimes store image as binary in Django database handy instead of the file.

There is this saying that storing images as binary in database is bad idea but I say it will come in handy certain times. For example you wanted to transfer image to another place and transferring as base64 string images is super fast than transferring all the images at mass. In other words base64 string will be very large when compare to the physical image transfer over the wire. Now that we seen the pros and cons, let’s dive into how we can store Image as binary in Django and we will discuss about how to access that in the template as well. Also I will talk about below points most and I think that will cover most of the things that I covered.

  1. How to convert image to binary format?
  2. How to display binary image from Django database to Django template?
  3. How to edit the binary image in Django?
    Let’s talk about the first point. How do we convert an Image to binary in the first place. This is where the base64 comes into play.
import base64

binary_image = base64.b64encode(file.read())

In general you have to use Django forms or request.FILES to get the file from the POST method. Once you got converted to binary format you can save into database. In Django database we have BinaryField that way we can store that as the binary format instead of the text format.

binary_image = models.BinaryField()

To display image in the Django template you have to use img src to display image.

  const decodedImageString = "{{ form.instance.binary_image.decode }}";
  
  var image = new Image();
  image.src = `data:image/png;base64,${decodedImageString}`;
  
  const updateImageHere = document.getElementById("updateImageHere")
  updateImageHere.appendChild(image);

Note that I have used the decode there to get the normal text from the BinaryField.

This article published under development on django tags. If you wish to receive email from me when I post a new blog post then please subscribe to my newsletter.


You might also like