【问题标题】: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

“优化”标志将尽可能减小其大小。

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 2019-12-02
    • 2018-09-13
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    相关资源
    最近更新 更多