如果图像大小为GT 300KB,则django-imagekit压缩图像

问题描述 投票:2回答:2

我已经设法安装(经过很多努力)django-imagekit,我现在能够使用django-imagekit来压缩上传图像的文件大小。

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

当上传的图像大小为300Kb,1MB,2MB,3MB或更大时,有没有办法使用不同的文件压缩(django-imagekit将其称为质量)(我在想if / elseif / else语句确认图像的大小并在图像的大小(KB)越大的情况下应用更低的质量?10的文件压缩适用于较大尺寸的图像,但是对于较小尺寸的图像(例如25Kb),会严重降低图像的质量。

我甚至不确定如何编写代码以及我将放置实现此目的的代码。所以任何帮助将不胜感激。

这是我的相关models.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类的表单字段版本,但这不会上传图像。

这是我在将models.py代码更改回图像字段时尝试的表单代码(上面已注释掉):

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

class NameDetailsForm(forms.ModelForm):

    def __init__(self, available_languages, language_preference, file_required, *args, **kwargs):
        """
        available_languages should be a valid choices list
        """
        super(NameDetailsForm, self).__init__(*args, **kwargs)
        self.fields['language_code'] = forms.ChoiceField(choices=available_languages, initial=language_preference, label=_('Language'),)
        #self.fields['name_details_photograph'] = forms.FileField(label=_('Photograph'), required=file_required)
        self.fields['name_details_photograph'] = ProcessedImageField(label=_('Photograph'), required=file_required, spec_id='myapp:profile:name_details_photograph', options={'quality': 25}, processors=[Adjust(sharpness=1.1),])

    class Meta:
        model = NameDetails
python django image django-imagekit
2个回答
3
投票

我要提供的解决方案完全未经测试。它基于imagekit库的源代码。

options kwargImageSpec类用于将它传递给PIL的Image.save()

因此,对于动态options,你可以创建自己的Spec类,将options定义为property,并使用getter返回一个即时的options。就像是:

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

name_details_photograph = ProcessedImageField(
    upload_to=_get_name_details_photograph_upload_location, 
    null=True, 
    blank=True, 
    spec=ThumbnailSpec
)

3
投票

您可以使用processor django创建自定义imagekit,然后在您的模型中使用它。 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中,添加处理器 -

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

class NameDetailsForm(forms.ModelForm):

def __init__(self, available_languages, language_preference, file_required, *args, **kwargs):
    """
    available_languages should be a valid choices list
    """
    super(NameDetailsForm, self).__init__(*args, **kwargs)
    self.fields['language_code'] = forms.ChoiceField(choices=available_languages, initial=language_preference, label=_('Language'),)
    #self.fields['name_details_photograph'] = forms.FileField(label=_('Photograph'), required=file_required)
    self.fields['name_details_photograph'] = ProcessedImageField(label=_('Photograph'), required=file_required, spec_id='myapp:profile:name_details_photograph', options={'quality': 25}, processors=[Adjust(sharpness=1.1), ConditionalResize(min_size=1000)])

class Meta:
    model = NameDetails

我还没有测试过这段代码,但应该可以解决你的问题。如果没有,请告诉我。

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

© www.soinside.com 2019 - 2024. All rights reserved.