have been going through many tutorials on python on how to compress images, Have used PILLOW but its not working. I will be grateful if I can get a full documentation on how to use PILLOW for image compression inside my django views.py
i had used thumbnail() in pillow to compress images previously inside models.py The thumbnail() doesnt change the aspect ratio of image when resizing the image.
import sys
from django.db import models
from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
def compressImage(uploaded_image):
image_temp = Image.open(uploaded_image)
outputIoStream = BytesIO()
image_temp.thumbnail( (1600,1600) )
image_temp.save(outputIoStream , format='JPEG', quality=100)
outputIoStream.seek(0)
uploaded_image = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % uploaded_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)
return uploaded_image
class ABC(models.Model):
name = models.CharField(max_length=200)
image = models.ImageField(upload_to=/upload/path/here/, null=True, blank=True)
def save(self, *args, **kwargs):
if not self.id:
self.image = compressImage(self.image)
super(ABC, self).save(*args, **kwargs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With