over 1 year ago

Found an excellent snippet here by monikkinom, which compresses all uploaded images to jpg before saving to disk:

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)

According to the official doc, the parameters for the InMemoryUploadedFile are:

file, field_name, name, content_type, size, charset, content_type_extra=None

Bonus

If you want to scale the image and still keeps its aspect ratio:

new_width = 800
img.thumbnail((new_wdith, new_width * self.image.height / self.image.width), Img.ANTIALIAS)
← JavaScript Iterator How to setup pypi server →
 
comments powered by Disqus