Skip to content

Instantly share code, notes, and snippets.

@uglyrobot
Created March 16, 2015 17:18
Show Gist options
  • Save uglyrobot/5a9395e5148ee7fab877 to your computer and use it in GitHub Desktop.
Save uglyrobot/5a9395e5148ee7fab877 to your computer and use it in GitHub Desktop.
Cronjob for optimizing image uploads
#!/bin/bash
FOLDER1='/somepath/wp-content/uploads/'
FOLDER2='/somepath/wp-content/uploads/'
#pngs
for i in `find $FOLDER1 $FOLDER2 -mmin -1 -iname '*.png'`
do
BEFORE_SIZE=$(stat -c%s "$i")
optipng -o2 -preserve -quiet $i
AFTER_SIZE=$(stat -c%s "$i")
REDUCTION=$((BEFORE_SIZE-AFTER_SIZE))
PERCENT=$(awk "BEGIN {printf \"%.2f\n\", ($REDUCTION/$BEFORE_SIZE)*100}")
TIME=$(date +"%Y-%m-%d %T")
echo "$TIME $i reduced by $REDUCTION bytes ($PERCENT%)" >> /tmp/smush.log
done
#jpgs
for i in `find $FOLDER1 $FOLDER2 -mmin -1 -iname '*.jpg'`
do
LOG=$(jpegoptim --max=90 --strip-all --preserve $i)
TIME=$(date +"%Y-%m-%d %T")
echo "$TIME $LOG" >> /tmp/smush.log
done
#gifs and preserve timestamps
for i in `find $FOLDER1 $FOLDER2 -mmin -1 -iname '*.gif'`
do
datemod=`stat $i | grep Modify | awk '{print $2,$3}'`
BEFORE_SIZE=$(stat -c%s "$i")
gifsicle -b -O3 $i
touch -d $datemod $i
AFTER_SIZE=$(stat -c%s "$i")
REDUCTION=$((BEFORE_SIZE-AFTER_SIZE))
PERCENT=$(awk "BEGIN {printf \"%.2f\n\", ($REDUCTION/$BEFORE_SIZE)*100}")
TIME=$(date +"%Y-%m-%d %T")
echo "$TIME $i reduced by $REDUCTION bytes ($PERCENT%)" >> /tmp/smush.log
done
exit 0
@uglyrobot
Copy link
Author

Looks for images added in last minute in your upload dirs, and processes them, preserving timestamps so they only get optimized once.

Run as a 1 minute cronjob. Requires optipng, jpegoptim, gifsicle packages installed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment