#!/bin/bash
# Script to optimize / reduce size of images
# Strip comments from images to save space
# uses: jpegoptim, optipng, pngcrush and jpegtran commands
# Note its always a good idea to not use default binary commands from Distro install
# but custom compile tools this would assure they're up2date many Linux distros like Debian include 
# tools version already 2 to 4 years old
# make sure all of them are installed and prsent on system before proceeding
#
# Script is suitable to run periodically as a cronjob especially on servers with hundred of thousand of users
# uploaded pictures
# Sample Cron to set:
# # crontab -u root -e 
# 00 3 10,27 * * /usr/sbin/optimize_images.sh 2>&1 >/dev/null
# Above sets the script to run twice a month on 10th and 27th date in 3:00 AM

IMG_DIR='/var/www/images/';
LOG_FILE='/var/log/optimize-images.log';

echo `date` >> $LOG_FILE
# optimize png images with optipng
find $IMG_DIR -mtime -2 -iname '*.png' -print0 | \
xargs -0 optipng -o7 -log $LOG_FILE -preserve
echo `date` >> $LOG_FILE
# optimize all jpeg images with jpegoptim
find $IMG_DIR -mtime -2 -iname '*.jpg' -print0 | \
xargs -0 jpegoptim --max=95 --preserve --totals >> $LOG_FILE
# optimize all png images with pngcrush
for png in `find $IMG_DIR -iname "*.png"`; do
    echo "crushing $png ..."
	    pngcrush -rem alla -reduce -brute "$png" temp.png
		 
    # preserve original on error
    if [ $? = 0 ]; then
        mv -f temp.png $png
	    else
        rm temp.png
	    fi
done

# optimize all png images with jpegtran
for jpg in `find $1 -iname "*.jpg"`; do
    echo "crushing $jpg ..."
	    jpegtran -copy none -optimize -perfect "$jpg" > temp.jpg
		 
    # preserve original on error
    if [ $? = 0 ]; then
	    mv -f temp.jpg $jpg
	    else
        rm temp.jpg
    fi
done
