Created
May 17, 2023 03:59
-
-
Save Anjaan-g/232e43daff13496f1ca298123fcfa07b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is the code to resize images on upload with Django Python. Works with both local files and cloud storages like S3. | |
import PIL | |
from django.db import models | |
from django.utils.translation import gettext_lazy as _ | |
class Image(models.Model): | |
name = models.CharField(_("Name"), max_length=254) | |
image = models.ImageField(_("Image"), upload_to="images", blank=True, null=True) | |
def __str__(self) -> str: | |
return self.name | |
def save(self, *args, **kwargs) -> None: | |
super().save(*args, **kwargs) | |
img = PIL.Image.open(self.image) | |
width, height = img.size | |
target_width = 600 | |
h_coefficient = width/600 | |
target_height = height/h_coefficient | |
img = img.resize((int(target_width), int(target_height)), PIL.Image.ANTIALIASING) | |
img.save(self.image.path, qulatity=100) | |
img.close() | |
self.image.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment