【问题标题】:Python Pillow: Make image progressive saving to modelPython Pillow:使图像渐进式保存到模型
【发布时间】:2015-10-24 13:02:09
【问题描述】:

我之前问过一个相对的问题,关于pillow

Python Pillow: Make image progressive before sending to 3rd party server

只是为了扩展这一点,当我上传图像并将其存储在服务器上时,如何将progressiveness 放入图像中?

模型.py

​​>
class Blog(models.Model):
    banner = models.FileField("banner", upload_to='blog_banner', help_text='Upload blog banner', blank=True, null=True)

Forms.py

​​>
def clean(self):
        data = self.cleaned_data
        banner = data['banner']

        # Check and make banner image progressive
        if not Utils.is_progressive_img(banner):
            data['banner'] = Utils.make_progressive_img(banner)

渐进法

img = Image.open(source)
progressive_img = StringIO()
img.save(progressive_img, "JPEG", quality=80, optimize=True, progressive=True)

forms.py 中,当我保存博客文章时,我看到以下错误,我知道这是由于StringIO() 的格式造成的

错误

AttributeError at /blog/create/
StringIO instance has no attribute '_committed'

【问题讨论】:

  • 我也有这个错误,看看这个答案也许会有所帮助(注意在python3中没有StringIO ...而是BytesIO ...但是想法应该是一样的)stackoverflow.com/a/30435175/3033586

标签: python django models filefield stringio


【解决方案1】:

这是我在forms.py中使用的解决方案

forms.py

​​>
def clean(self):
    data = self.cleaned_data
    banner = data['banner']

    # Blog banner has been changed, Check for if the new image is progressive?
    if self.instance.banner != banner and Utils.is_progressive_img(banner) is False:
        progressive_banner = Utils.make_progressive_img(img=banner, method=2)
        data['banner'].file = progressive_banner

   return data

您需要更新 Django FileField.file 属性

models.py

​​>
class Blog(models.Model):
    banner = models.FileField("banner", upload_to='blog_banner', help_text='Upload blog banner', blank=True, null=True)

更新

model.save()中实现同样的逻辑

if Utils.is_progressive_img(self.banner) is False:
     progressive_banner = Utils.make_progressive_img(img=self.banner, method=2)

     name = self.banner.name
     # Delete the current image & Add the new progressive image.
     self.banner.delete(save=False)
     self.banner.save(name,content=ContentFile(progressive_banner.getvalue()), save=False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多