Tuesday, September 4, 2012

[Tutorial] How optimize images JPG/PNG/GIF on Linux using littleutils package centos 7.x


Littleutils package contains couple of little utils useful for production websites.
I've used the opt-png, opt-jpg, opt-gif to reduce and optimize the size of images on some high trafficed websites without any quality loss.

# Install pngcrush :
cd /usr/src
wget https://sourceforge.net/projects/pmt/files/pngcrush/1.8.10/pngcrush-1.8.10.tar.gz
tar -zxf pngcrush-1.8.10.tar.gz
cd pngcrush-1.8.10
chown -R nobody /usr/src/pngcrush-1.8.10
sudo -u nobody make
cp pngcrush /usr/local/bin


yum install libpng-devel gifsicle lzip libjpeg-turbo-utils
cd /usr/src
wget http://downloads.sourceforge.net/project/littleutils/littleutils-source/1.0.36/littleutils-1.0.36.tar.bz2
tar -jxf littleutils-1.0.36.tar.bz2
cd littleutils-1.0.36
./configure
chown -R nobody /usr/src/littleutils-1.0.36

sudo -u nobody make
make install
make install-extra


The following script first backup all images in the /home folder, then optimize each one :


#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
cd /home;
NOW=$(date +"%d-%m-%Y");
echo -e "Backup images ...\nBackup file : ./backup-pictures-$NOW.tar";
`find . -regextype posix-extended -iregex "(.*?)\.(gif|jpe?g|png)" -print | tar -cf backup-pictures-$NOW.tar -T -`;
echo "" > log;
echo -e "Backup size is :";
echo `du -hs ./backup-pictures-$NOW.tar`;
echo -e "\nStart optimizing images ...\nLog file: ./log"
pics=`find . -regextype posix-extended -iregex "(.*?)\.(gif|jpe?g|png)"`;
for pic in $pics; do
        type=`file "$pic" | awk '{print $2}' | tr '[:upper:]' '[:lower:]'`;
        case $type in
                        "gif" )
                                        opt-gif "$pic" >> log
                                        ;;
                        "png" )
                                        opt-png "$pic" >> log
                                        ;;
                        "jpeg" )
                                        opt-jpg "$pic" >> log
                                        ;;

                        *)
                                        echo -e "file $pic which has type $type is undefined" >> log

                                        ;;
        esac
done
IFS=$SAVEIFS

No comments:

Post a Comment