0

I have multiple images upload in my Database, and when I am uploading image in Django then it's reducing the size of image (eg: 200km to 90 kb), but suppose if image size is 1000*800 then it's saving in the same size. I want to resize it with 600*400, Please let me know where I am mistaking in this code. please check my code, here are my models.py file

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

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)
    outputIoStream = BytesIO()
    imageTemproaryResized = imageTemproary.resize((600, 400))
    imageTemproary.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
saini tor
  • 223
  • 6
  • 21

1 Answers1

0

I can't pin point where the problem is, I myself is a newbie. but you can try this, it should work.

def compressImage(self, image):
    image_file = BytesIO(image.file.read())
    n_image = Image.open(image_file)
    n_image.thumbnail((600, 400), Image.ANTIALIAS)
    image_file = BytesIO()
    n_image.save(image_file, 'JPEG')
    return image_file
mursalin
  • 1,151
  • 1
  • 7
  • 18