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 models.py 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)
image=models.ImageField(upload_to='product_image',blank=False,null=True)
def save(self, *args, **kwargs):
if not self.id:
self.image = self.compressImage(self.image)
super(ProductImage, self).save(*args, **kwargs)
def compressImage(self, image):
imageTemproary = Image.open(image)
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))
imageTemproaryResized.save(outputIoStream, format='JPEG', quality=60)
outputIoStream.seek(0)
image = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.jpg" % image.name.split('.')[0],
'image/jpeg', sys.getsizeof(outputIoStream), None)
return image
# def __str__(self):
# return self.product.name
Our Views.py 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):
subcat=SubCategory.objects.all()
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 = form.save(commit=False)
newpost.slug = slugify(newpost.name)
newpost.save()
form.save_m2m()
context={
'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)