Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jpegoptim with PIL in easy-thumbnails

I'd like to process all JPEG thumbnails generated with easy-thumbnail via PIL thru jpegoptim.

Using PIL's optimization: image.save(..,optimize=1,...) isn't optimizing much at all.

For example:

  • with PIL: 123KB
  • with PIL + optimize: 112KB
  • with PIL + optimize + jpegoptim: 52KB

Can anyone point me to Python examples or libraries that integrate jpegoptim?

like image 970
Steve McKinney Avatar asked Mar 14 '26 05:03

Steve McKinney


1 Answers

You can use thumbnail_created signal and call external app via subporecess.Popen. I just realize this in my project. You can even optimize images when they uploaded using saved_file signal!

Here is my code:

import subprocess
from os.path import splitext

from django.dispatch import receiver
from easy_thumbnails.signals import saved_file, thumbnail_created

@receiver(saved_file)
def optimize_file(sender, fieldfile, **kwargs):
    optimize(fieldfile.path)

@receiver(thumbnail_created)
def optimize_thumbnail(sender, **kwargs):
    optimize(sender.path)

def optimize(path):
    runString = {
        ".jpeg": u"jpegoptim -f --strip-all '%(file)s'",
        ".jpg": u"jpegoptim -f --strip-all '%(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'"
    }

    ext = splitext(path)[1].lower()
    if ext in runString:
        subprocess.Popen(runString[ext] % {'file': path}, shell=True)

runString taken from trimage. On Debian, you need to install following packages: jpegoptim optipng pngcrush advancecomp. Or just use another tools, such as smush.py.


I also found this project which encapsulates code above, has gif support and better filetype recognition.

like image 131
neoascetic Avatar answered Mar 17 '26 01:03

neoascetic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!