djangimagekit压缩图像(如果图像大小大于300KB)

2024-05-16 11:13:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经成功地安装了django-imagekit,现在我可以使用django-imagekit来压缩上传图像的文件大小。在

我可以上传一个6MB的图像,django-imagekit将压缩到230KB当我使用质量为10(见下文)。在

当上传的图像大小为300Kb、1MB、2MB、3MB或更大时,是否有一种方法可以使用不同的文件压缩(django imagekit将其称为质量)(我正在考虑一个if/elseif/else语句,它将确认图像的大小,并对图像的大小(KB)应用较低的质量?对于较大尺寸的图像,10的文件压缩效果很好,但对于较小尺寸的图像(例如25Kb),则会从根本上降低图像的质量。在

我甚至不确定我将如何编写代码,以及我将把代码放在什么地方来实现这一点。因此,任何帮助都将不胜感激。在

这是我的相关资料模型.py文件编码:

from imagekit.processors import Adjust, ResizeToFill
from imagekit.models import ProcessedImageField

class NameDetails(models.Model, FillableModelWithLanguageVersion):
    user = models.ForeignKey(User)
    ....
    #name_details_photograph = models.ImageField(upload_to=_get_name_details_photograph_upload_location, null=True, blank=True)
    name_details_photograph = ProcessedImageField(upload_to=_get_name_details_photograph_upload_location, null=True, blank=True, options={'quality': 25}, processors=[Adjust(sharpness=1.1),])
    ....

    def __unicode__(self):
        return unicode(self.user)

编辑:

我试图实现ProcessedImageField类的表单字段版本,但这不会上载图像。在

这是我在更改模型.py将代码返回到图像字段(上面已注释掉):

^{pr2}$

Tags: 文件django代码name模型图像truemodels
2条回答

我要提供的解决方案完全没有经过测试。它基于^{}库的源代码。在

optionskwarg^{}类用来传递给PIL的Image.save()。在

因此,对于动态options,您可以创建自己的Spec类,将options定义为property,并使用getter动态返回{}。比如:

from imagekit import ImageSpec
from imagekit.processors import Adjust, ResizeToFill

class ThumbnailSpec(ImageSpec):
    format = 'JPEG'
    options={'quality': 50}
    processors=[Adjust(sharpness=1.1),]

    @property
    def options(self):
        options = self._options
        #You can create some checks here and choose to change the options
        #you can access the file with self.source
        if self.source.size > 2*100*100:
            options['quality'] -= 25
        return options
    @options.setter
    def options(self, value):
        self._options = value

最后使用您的ThumbnailSpec,方法是将它传递给ProcessedImageField

^{pr2}$

您可以使用djangoimagekit创建一个自定义的processor,然后在模型中使用它。processor将检查图像的大小,然后返回已编辑的图像。像这样-

class ConditionalResizer(object):
    min_size = None  # minimum size to reduce in KB
    def __init__(self, *args, min_size=1000, **kwargs):
        super().__init__(self, *args, **kwargs) # code is for python > 3.0, modify for python < 3.0 as necessary 
        self.min_size = min_size

    def process(self, image):
        size = # code to get size of image
        if size > self.min_size:
            # process the image
            image = # processed image
        return image

然后在Form中,添加处理器-

^{pr2}$

我还没有测试这个代码,但应该能够解决你的问题。如果没有请告诉我。在

您可以在这里找到有关处理器的更多信息-https://django-imagekit.readthedocs.org/en/latest/#processors

相关问题 更多 >