Login

Image compression before saving the new model / work with JPG, PNG

Author:
Schleidens
Posted:
May 24, 2023
Language:
Python
Version:
3.2
Score:
0 (after 0 ratings)

Don't forget to replace "self.image" by your image field name from your model ex ( self.cover ) replace Product by your model name

works pretty well :)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#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)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 1 month, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 month, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 8 months, 2 weeks ago
  4. Help text hyperlinks by sa2812 10 months ago
  5. Stuff by NixonDash 1 year ago

Comments

Please login first before commenting.