How to Compress Images in Django?

How to Upload Multiple Images in Django?

Today We will learn how to compress image in Django, so first Install the python image handling library Pillow

use this command for install Pillow:  pip install Pillow

Our looks like,

import sys
from django.db import models
from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.utils.text import slugify

class ProductImage(models.Model):
    product=models.ForeignKey(Product, default=None, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        if not
            self.image = self.compressImage(self.image)
        super(ProductImage, self).save(*args, **kwargs)

    def compressImage(self, image):
        imageTemproary =
        if imageTemproary.mode in ("RGBA", "P"):
         imageTemproary = imageTemproary.convert("RGBA") #this code will convert all png files to JPG
        outputIoStream = BytesIO()
        imageTemproaryResized = imageTemproary.resize((1020, 573)), format='JPEG', quality=60)
        image = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.jpg" %'.')[0],
                                             'image/jpeg', sys.getsizeof(outputIoStream), None)
        return image
    # def __str__(self):
    #     return

Our file look like this

from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from .models importSubCategory, Product, ProductImage
from .forms import ProductForm

def create_product(request):
    common_tags = Product.tags.most_common()[:4]
    form = ProductForm(request.POST, request.FILES) # request.FILES wil save the images in database
    if form.is_valid():
        newpost =
        newpost.slug = slugify(
        'subcat':subcat, 'common_tags':common_tags, 'form':form,
    return render(request, 'home.html', context)

Not upload product in your database, and check the uploaded image (if a image size is 500kb then it will be convert approximate 230 kb)


Please enter your comment!
Please enter your name here