Compress Images In The Background using Django

Md Mahmudul Huq Topu
2 min readDec 27, 2019

--

This is a very short tutorial where I’ll be describing about the image compression technique using Python’s famous Pillow library. We will be adding some simple lines of code which will enhance our Model with image compression facility. The image will be automatically compressed in the background before getting saved.
For this we need to have Pillow library installed on the environment. To install this library you just need to execute this command

pip install Pillow

So here is our simple gallery model

Here, we have imported couple of libraries at the beginning.

from io import BytesIO  #basic input/output operation
from PIL import Image #Imported to compress images
from django.core.files import File #to store files

After importing these, we need to create a method/function which will take images as input and deliver compressed images as output.

#image compression method
def compress(image):
im = Image.open(image)
im_io = BytesIO()
im.save(im_io, 'JPEG', quality=60)
new_image = File(im_io, name=image.name)
return new_image

this function/method takes the image as argument/parameter and then it compresses according to our choices. First, im object is created by getting the image opened. Then we create another object im_io from BytesIO class. Using the object “im” we need to compress the image by calling the method save() having three argument.

im.save(im_io, 'JPEG', quality=60)

Here, it takes three parameters, first one is the object instantiate from BytesIO class, second the image format we want as the output, third one the quality of the images we want to have after getting compressed in percentage.
Finally, we store and return the name of the compressed image.

So, the question is how to call this method inside a model ? The answer is pretty simple, all you need is to override the save() method of the desired model.

#calling image compression function before saving the data    
def save(self, *args, **kwargs):
new_image = compress(self.image)
self.image = new_image
super().save(*args, **kwargs)

So, it basically sends the images to the compress() method and wait for the response, after getting the response it stores the entire model’s data.

Here is the final result.

Actual Size Before Uploading The Image (Size: 1.67 MB)
Size After Getting Compressed (Size 69.53 KB)

You can use this technique anywhere,even for compressing images of text editors too.

--

--

Md Mahmudul Huq Topu
Md Mahmudul Huq Topu

Written by Md Mahmudul Huq Topu

I’m a Full Stack Software Engineer at Skill Jobs.Also do youtubing(Metacentric Bangladesh) since 2014.

Responses (2)