Skip to main content

Optimize images with cronjob

With image styles and responsive breakpoints drupal generates automatically smaller images from the original uploaded ones. Depending on the formatter and the responsive images settings, the visitor already get's optimized images in the browser.

Most of my customers want sites with imagesliders in the background, each showing a set of wonderful images they uploaded themselves. Even if drupal serves smaller images, the pageload for such sites does not please Google Page Speed at all.

A possible solution is to reduce the filesize of the automatically generated images in the background with a cronjob and some nice utilities on the server.

Create a bash script which cd's into the styles directory of your drupal site. Then run:

find . -name "*.jpg" | xargs jpegoptim --strip-all --all-progressive --preserve; find -name '*.png' | xargs optipng -o2 -strip all -preserve 

jpegoptim and optipng have to be installed at the server of course.

If you run this script in a regular interval it's recommendable to include -mtime option in find command. jpegoptim is very fast but optipng needs lots of CPU on each run.