简体   繁体   中英

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?

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.

I found https://github.com/thebeansgroup/smush.py which is a lossless image optimiser in Python >=2.7. I went with https://github.com/beatak/smush.py which is a fork that works for Python >= 2.5, since we are using debian stable on our server.

It uses:

Hopefully using pngnq multiple times on files doesn't degrade quality, we plan to run this script on all uploaded media weekly.

I doubt that there are any python bindings to jpegoptim. The options I can think of are:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM