How to convert image to specific file size?

I work with Pillow , Django and django-imagekit .

I am looking to have a profile model field (possibly using the ProcessedImageField class from imagekit) that will accept any image, convert to JPEG, crop it to 150x150 and make its file size 5KB.

The first two are easy:

 profile_picture = imagekit.models.ProcessedImageField(upload_to=get_profile_picture_file_path, format='JPEG', processors=[ResizeToFill(height=150, width=150)] ) 

But how can I provide a file size of 5 KB? I could use something like the options={'quality': 60} parameter in the ProcessedImageField , but this only looks like the original file size (as far as I know).

Solutions do not need to use django-imagekit, but that would be preferable.

+5
source share
2 answers

Maybe that way. Check the size of the image after downloading and deleting it or reduce it in the overridden save method:

 class Images(models.Model): profile_picture = imagekit.models.ProcessedImageField(upload_to=get_profile_picture_file_path, format='JPEG', processors=[ResizeToFill(height=150, width=150)] ) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if os.stat(get_profile_picture_file_path + "/" + self.profile_picture.new_name).st_size > max_size: do_something_further_image_processing_to_decrease_size super(Images, self).save() 
0
source

I had a similar problem, so I decided to optimize images using OS tools (jpegoptim, optipng, etc.) called from django after saving the model using signals (you can also override the save method). These tools optimize and eliminate metadata from your images. On the other hand, you can study the average compression ratio and size for jpg files 150x150 and try to guess the best quality for customization. Check this out: ( jpeg compression ratio )

This is my code for optimizing files after saving them. I use a convenient thumbnail that provides me with signals after saving:

 @receiver(saved_file) def optimize_file(sender, fieldfile, **kwargs): optimize(fieldfile.path) # thumbnail optimization @receiver(thumbnail_created) def optimize_thumbnail(sender, **kwargs): optimize(sender.path) def optimize(path): """ install image utilities apt-get install jpegoptim optipng pngcrush advancecomp :param path: :return: """ # taken from trimage (http://trimage.org/) runString = { ".jpeg": u"jpegoptim -f --strip-all '%(file)s' ; chmod 644 '%(file)s'", ".jpg": u"jpegoptim -f --strip-all '%(file)s' ; chmod 644 '%(file)s'", ".png": u"optipng -force -o7 '%(file)s' && advpng -z4 '%(file)s' && pngcrush -rem gAMA -rem alla -rem cHRM -rem iCCP -rem sRGB -rem time '%(file)s' '%(file)s.bak' && mv '%(file)s.bak' '%(file)s' ; chmod 644 '%(file)s'" } ext = splitext(path)[1].lower() if ext in runString: subprocess.Popen(runString[ext] % {'file': path}, shell=True) 
0
source

Source: https://habr.com/ru/post/1243087/


All Articles