0

I asked a relative question previously, regarding pillow.

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

Just to extend this, How can I achive the progressiveness into the image when I am uploading an image and storing it on the sever?

Models.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)

Progressive Method

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

in forms.py when i save the the blog post i see the following error and I know this is due the the format of StringIO()

Error

AttributeError at /blog/create/
StringIO instance has no attribute '_committed'
Community
  • 1
  • 1
A.J.
  • 8,557
  • 11
  • 61
  • 89
  • 1
    I also had this error, look at this answer maybe it will help (note in python3 there is not StringIO ... there is BytesIO instead ... but idea should be same) http://stackoverflow.com/a/30435175/3033586 – madzohan Aug 02 '15 at 12:01

1 Answers1

0

Here is the SOLUTION which i used in the 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

You need to update the .file property of the Django FileField

models.py

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

Update

Impliment the same logic in 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)
A.J.
  • 8,557
  • 11
  • 61
  • 89