【问题标题】:how to compress user uploaded image with Pillow in Django rest framework如何在 Django REST 框架中使用 Pillow 压缩用户上传的图像
【发布时间】:2020-05-05 10:38:55
【问题描述】:
当用户上传时你会如何压缩图片
from PIL import Image
class photo(models.Model):
title = models.CharField(max_length=100)
uploader = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
image_url = models.ImageField(upload_to='images', null=True)
【问题讨论】:
标签:
django
django-rest-framework
python-imaging-library
【解决方案1】:
在保存方法中做
from PIL import Image
class photo(models.Model):
title = models.CharField(max_length=100)
uploader = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
image_url = models.ImageField(upload_to='images/', null=True)
def save(self, *args, **kwargs):
instance = super(photo, self).save(*args, **kwargs)
img = Image.open(instance.image_url.path)
img.save(instance.image_url.path,quality=20,optimize=True)
return instance
“优化”标志将尽可能减小其大小。