Skip to content

Instantly share code, notes, and snippets.

@drdim
Last active December 16, 2015 15:39
Show Gist options
  • Save drdim/5457420 to your computer and use it in GitHub Desktop.
Save drdim/5457420 to your computer and use it in GitHub Desktop.
Image Optimisation script used utils, optipng,
#!/bin/bash
DIR=$1;
DIR=`echo $1 |sed -e 's,\(.\)/$,\1,'`
back() {
mkdir "$DIR.old";
for i in `ls $DIR`;
do
cp -r $DIR/$i $DIR.old;
done;
echo "Your files copied to $DIR.old...."
}
tran() {
echo "Start OPTIMIZING...."
for file
in `find $DIR -iname "*.jpg" -or -iname "*.png" -or -iname "*.jpeg" -or -iname "*.gif"`;
do
if [ -z "$file" ]; then
echo "Usage: optimize-image.sh filename"
exit 1;
fi
if [ ! -f "$file" ]; then
echo "$file is not a file"
exit 1;
fi
TYPE=`identify "$file" | grep -E -o 'JPEG|GIF|PNG'`
OLD=`stat -c %s "$file"`
case "$TYPE" in
JPEG)
jpegtran -copy none -optimize -perfect -progressive -outfile "$file.tmp" "$file"
jpegtran -copy none -optimize -perfect -outfile "$file.tmq" "$file"
if [ -f "$file.tmp" -a -f "$file.tmq" ]; then
S_PROG=`stat -c %s "$file.tmp"`
S_NORM=`stat -c %s "$file.tmq"`
if [ $S_PROG -ge $S_NORM ]; then
mv -f "$file.tmq" "$file"
rm -f "$file.tmp"
else
mv -f "$file.tmp" "$file"
rm -f "$file.tmq"
fi;
fi
;;
GIF)
gifsicle -O2 -b "$file"
;;
PNG)
optipng "$file"
advpng -z -4 -q "$file"
;;
esac
NEW=`stat -c %s "$file"`
echo "$file, old size: $OLD, new size: $NEW"
done;
echo "OPTIMIZE IS DONE!";
echo "You can find your files before optimization in $DIR.old"
}
dojob() {
if [ -z "$DIR" ]; then
echo "Script usage: ./optimize-image.sh /dirname"
exit 1
else
back
tran
fi
}
echo "Script is starting...."
dojob
echo "Script job finished"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment