【问题标题】:How to compress uploaded image in django python如何在 django python 中压缩上传的图像
【发布时间】:2018-09-13 18:16:54
【问题描述】:

已经阅读了许多关于如何压缩图像的 python 教程,使用过 PILLOW 但它不起作用。如果我能在我的 django views.py 中获得有关如何使用 PILLOW 进行图像压缩的完整文档,我将不胜感激

【问题讨论】:

  • 您是如何尝试PILLOW 的,它是如何失败的?我的意思是,您是否有一些代码和一些您遇到的错误的堆栈跟踪?这样解决问题会更容易。
  • 它不起作用还不够,你需要提供一个不起作用的例子。除此之外,您可能还想使用现有的库之一,例如 easy-thumbnails、sorl-thumbnail 或类似的东西。
  • from PIL import Image a = request.FILES['image'] with Image.open(a) as image: image.thumbnail((400,400),Image.ANTIALIAS) b = image.save( output,format="JPEG") thumbnail_string = base64.b64encode(output.getvalue()).decode() product.image = thumbnail_string print(thumbnail_string) product.save()
  • 问题是我试图接受来自用户的图像,并且我想在将其保存到我的数据库之前压缩/减少字节。

标签: django python-3.x web django-templates


【解决方案1】:

我之前在枕头中使用 thumbnail() 来压缩模型中的图像。py 调整图像大小时,thumbnail() 不会改变图像的纵横比。

import sys

from django.db import models
from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile

def compressImage(uploaded_image):
    image_temp = Image.open(uploaded_image)
    outputIoStream = BytesIO()
    image_temp.thumbnail( (1600,1600) )
    image_temp.save(outputIoStream , format='JPEG', quality=100)
    outputIoStream.seek(0)
    uploaded_image = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % uploaded_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)
    return uploaded_image

class ABC(models.Model):
    name = models.CharField(max_length=200)
    image = models.ImageField(upload_to=/upload/path/here/, null=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.id:
            self.image = compressImage(self.image)
        super(ABC, self).save(*args, **kwargs)

【讨论】:

    猜你喜欢
    • 2019-02-10
    • 2011-05-20
    • 2016-01-09
    • 1970-01-01
    • 2018-09-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多