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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With