You can save space on server & speed up your speed by saving a thumbnail of an image. Sometimes we don't want to save images with size of 3 MB or 5 MB or even more, so can save just a thumbnail of that image for better performance of our app:
from PIL import Image # pip install pillow
class Profile(models.Model):
# other fields
image = models.ImageField(upload_to="path/to/be/saved")
def save(self, *args, **kwargs):
super(Profile, self).save(*args, **kwargs)
img = Image.open(self.image)
if img.height > 200 or img.width > 200:
new_size = (200, 200)
# image proportion is manteined / we dont need to do extra work
img.thumbnail(new_size)
img.save(self.image.path)
This code overrides the Django model's save method. After the original image is saved, it opens the file using the Pillow library (PIL.Image). It then checks if the image's dimensions exceed 200 pixels in height or width. If they do, it creates a thumbnail with a maximum size of 200x200 pixels, which maintains the original aspect ratio, and then overwrites the original file with this new, smaller version.
