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.
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 |