Skip to content

Instantly share code, notes, and snippets.

@jlaustill
Last active July 26, 2017 18:47
Show Gist options
  • Save jlaustill/068949b25120fad57ec5c1dcd59d1958 to your computer and use it in GitHub Desktop.
Save jlaustill/068949b25120fad57ec5c1dcd59d1958 to your computer and use it in GitHub Desktop.
A simple script to recursively optimize every image(jpeg|gif|png) in a folder.

This simple script will find every jpg, gif, and png in a directory recursively and optimize it using google's pagespeed recommended settings.

Depends on ImageMagick's convert plugin. Pass folder to optimize as first parameter.

#!/bin/bash
if (( $# != 1 ))
then
echo "Script requires exactly one argument, which is a valid path to optimize."
exit 1;
else
if [ ! -d $1 ]; then
echo "Directory must exist!."
exit 1;
fi
fi
echo "Optimizing JPG images now..."
find $1 -name "*.jpg" -print0 | while IFS= read -r -d '' file
do
if [ ! -z "$file" ]; then
convert "$file" -sampling-factor 4:2:0 -quality 85 -strip -interlace JPEG -alpha Remove "$file.test"
FILESIZE=$(stat -c%s "$file")
FILESIZEM=$(stat -c%s "$file.test")
while (( FILESIZEM < FILESIZE ))
do
echo "Optimized image $file Before: $FILESIZE, After: $FILESIZEM"
cp "$file.test" "$file"
convert "$file" -sampling-factor 4:2:0 -quality 85 -strip -interlace JPEG -alpha Remove "$file.test"
FILESIZE=$(stat -c%s "$file")
FILESIZEM=$(stat -c%s "$file.test")
done
rm "$file.test"
fi
done
echo "Optimizing GIF images now..."
find $1 -name "*.gif" -print0 | while IFS= read -r -d '' file
do
if [ ! -z "$file" ]; then
convert "$file" -strip -alpha Remove "$file.test"
FILESIZE=$(stat -c%s "$file")
FILESIZEM=$(stat -c%s "$file.test")
if (( FILESIZEM < FILESIZE )); then
echo "Optimized image $file Before: $FILESIZE, After: $FILESIZEM"
cp "$file.test" "$file"
fi
rm "$file.test"
fi
done
echo "Optimizing PNG images now..."
find $1 -name "*.png" -print0 | while IFS= read -r -d '' file
do
if [ ! -z "$file" ]; then
convert "$file" -strip -alpha Remove "$file.test"
FILESIZE=$(stat -c%s "$file")
FILESIZEM=$(stat -c%s "$file.test")
if (( FILESIZEM < FILESIZE )); then
echo "Optimized image $file Before: $FILESIZE, After: $FILESIZEM"
cp "$file.test" "$file"
fi
rm "$file.test"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment