Issue
I have a project with Django and I use Pillow to store images in some models, but I want those images to be stored compressed. How can I instruct Pillow to compress the images when they are saved to a model ImageField?
This is an example of a model with an ImageField:
class Photo(models.Model):
name = models.CharField(max_length=100, null=True, blank=True, verbose_name=_("Name"))
album = models.ForeignKey(Album, on_delete=models.PROTECT, related_name='photos', verbose_name=_("Album"))
photo = models.ImageField(verbose_name=_("Photo"))
class Meta:
verbose_name = _("Photo")
verbose_name_plural =_("Photos")
def __str__(self):
return "[{}] {}".format(self.pk, self.name)
I can see the file once stored, and I can see it has the same size than the original source file.
I am using Django Rest Framework to get images from the front-end.
Solution
You can override save
method of the model:
from PIL import Image
class Photo(models.Model):
name = models.CharField(max_length=100, null=True, blank=True, verbose_name=_("Name"))
album = models.ForeignKey(Album, on_delete=models.PROTECT, related_name='photos', verbose_name=_("Album"))
photo = models.ImageField(verbose_name=_("Photo"))
def save(self, *args, **kwargs):
instance = super(Photo, self).save(*args, **kwargs)
image = Image.open(instance.photo.path)
image.save(instance.photo.path,quality=20,optimize=True)
return instance
Answered By - ruddra
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.