Skip to content

Instantly share code, notes, and snippets.

@Anjaan-g
Created May 17, 2023 03:59
Show Gist options
  • Save Anjaan-g/232e43daff13496f1ca298123fcfa07b to your computer and use it in GitHub Desktop.
Save Anjaan-g/232e43daff13496f1ca298123fcfa07b to your computer and use it in GitHub Desktop.
# 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