Last active
August 11, 2020 13:58
-
-
Save olivx/19450c280bfdbfc89f8a4b73558d9c0d to your computer and use it in GitHub Desktop.
Django resize thumbnail on save image
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
from io import BytesIO | |
from os.path import splitext | |
from uuid import uuid4 | |
from PIL import Image | |
def genereic_entity_upload_to(instance, filename): | |
_, filename_ext = splitext(filename) | |
return f"{instance.__class__.__name__}/{instance.entity.pk}/{uuid4()}.{filename_ext}".lower() | |
class EntityImage(Timestamp): | |
image = models.FileField( | |
"Image", upload_to=genereic_entity_upload_to, validators=[validate_ext_image], | |
blank=True, null=True | |
) | |
title = models.CharField("Titulo", max_length=100, blank=True, null=True) | |
summary = models.TextField("Resumo", blank=True, null=True) | |
entity = models.ForeignKey( | |
"core.Entity", on_delete=models.CASCADE, related_name="entity_images" | |
) | |
class Meta: | |
verbose_name = "Entidade Image" | |
verbose_name_plural = "Entidades Image" | |
def __str__(self): | |
return self.title | |
def save(self, *args, **kwargs): | |
buffer = BytesIO() | |
THUMBNAIL_SIZE = (300, 300) | |
image = Image.open(self.image.file) | |
image.convert("RGB") | |
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) | |
filename, ext = splitext(self.image.name.strip()) | |
_format = ext.replace(".", "") | |
if _format.lower() == "jpg": | |
_format = "JPEG" | |
image.save(buffer, format=_format) | |
file_object = File(buffer) | |
file_object.name = filename | |
file_object.content_type = f"image/{ext.lower()}" | |
self.image.save(f"{filename}.{ext}", file_object, save=False) | |
super(EntityImage, self).save(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment