Login

Image compression and conversion to JPG format before uploading the file

Author:
monikkinom
Posted:
January 26, 2015
Language:
Python
Version:
Not specified
Score:
3 (after 3 ratings)

I've reimplemented the code I found somewhere on the web within my models file. The earlier version was incapable of converting all formats to JPG while this code converts all formats and compresses all of them successfully.

You need to have PILLOW installed for this to work.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from PIL import Image as Img
import StringIO

class Images(models.Model):
    image = models.ImageField()

    def save(self, *args, **kwargs):
        if self.image:
            img = Img.open(StringIO.StringIO(self.image.read()))
            if img.mode != 'RGB':
                img = img.convert('RGB')
            img.thumbnail((self.image.width/1.5,self.image.height/1.5), Img.ANTIALIAS)
            output = StringIO.StringIO()
            img.save(output, format='JPEG', quality=70)
            output.seek(0)
            self.image= InMemoryUploadedFile(output,'ImageField', "%s.jpg" %self.image.name.split('.')[0], 'image/jpeg', output.len, None)
        super(Images, self).save(*args, **kwargs)

More like this

  1. codigo alto nivel by MrRocklion 1 month ago
  2. Load template from specific app by Krzysiek555 1 month, 3 weeks ago
  3. PostgreSQL JSON subqueries by dolamroth 1 month, 3 weeks ago
  4. "Magic Link" Management Command by webology 7 months ago
  5. Closest ORM models to a latitude/longitude point by simonw 7 months ago

Comments

Alphare (on December 1, 2015):

This is very good! Copy and paste, it just works.

#

JhonatanAcelas (on July 26, 2017):

This works really well !!! After 1 day looking for, excellent job

#

Please login first before commenting.