Login

Image compression and conversion to JPG format before uploading the file

Author:
monikkinom
Posted:
January 26, 2015
Language:
Python
Version:
1.7
Score:
0 (after 0 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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', "file.jpg", 'image/jpeg', output.len, None)
        super(Images, self).save(*args, **kwargs)

More like this

  1. Browser-native date input field by kytta 1 month, 1 week ago
  2. Generate and render HTML Table by LLyaudet 1 month, 2 weeks ago
  3. My firs Snippets by GutemaG 1 month, 3 weeks ago
  4. FileField having auto upload_to path by junaidmgithub 3 months ago
  5. LazyPrimaryKeyRelatedField by LLyaudet 3 months, 1 week ago

Comments

Saga032000 (on March 29, 2020):

can u help plz how make it in my project like folders

#

Please login first before commenting.