#import those on top of your models.py file

from PIL import Image
from io import BytesIO
from django.core.files import File

def image_compression(self, *args, **kwargs):
       if self.image:
            # Open the image using Pillow
            image = Image.open(self.image)
            
            #Resize the image to a maximum size of 1024 x 1024 pixels
            image.thumbnail((1024, 1024))
            
            # Compress the image
            if self.image.name.lower().endswith('.jpg') or self.image.name.lower().endswith('.jpeg'):
                format = 'JPEG'
                # Set the JPEG quality level to 80%
            elif self.image.name.lower().endswith('.png'):
                format = 'PNG'
                # Set the PNG compression level to 6 (out of 9)
                image = image.convert('P', palette=Image.ADAPTIVE, colors=256)
                options = {'compress_level': 6}
            else:
                # Unsupported image format
                super(Product, self).save(*args, **kwargs)
                return
            
            output = BytesIO()
            image.save(output, format=format, optimize=True, quality=80, **options if format == 'PNG' else {})
            new_image = File(output, name=self.image.name)

            # Set the image field to the compressed image
            self.image = new_image

            super(Product, self).save(*args, **kwargs)
    
    
    def save(self, *args, **kwargs):
        #calling your methods inside the save methods by django
        self.image_compression()
        super().save(*args, **kwargs)