Image compression script

Time:2020-11-12

1 Overview

Using the convert command to do a small image compression script, only one parameter is required to specify the compression quality, which will compress the JPG / jpeg / PNG of the current folder.

sh compress.sh 75

After the compression is completed, the maximum, minimum and average compression ratio are displayed.

2. Main processes

First determine whether there are pictures in the current folder and the number of pictures to be obtained:

picNums=`ls | grep -iE "*.jpg|*.png|*.jpeg" | grep -v "_compress" | wc -l`

Then calculate the original file size and separate the file name to get the main file name and suffix name

originalSize=`ls -l $i | awk '{print $5}'`
basename=`basename $i`
filename="${basename%.*}"
suffix="${basename##*.}"
compressFileName="$filename._compress.$suffix"

Then determine whether the main file name contains compress (compress will be added to the compressed file, and the original file will be retained), and then calculate the ratio:

convert -quality $1 $i $compressFileName
compressedSize=`ls -l $compressFileName | awk '{print $5}'`
ratio=$(printf "%.2f" `echo "scale=2;$compressedSize/$originalSize"|bc`)
if [[ `echo "$ratio<$minRatio" | bc` == 1 ]]
then
    minRatio=$ratio
fi
if [[ `echo "$ratio>$maxRatio" | bc` == 1 ]]
then
    maxRatio=$ratio
fi
totalRatio=`echo "$totalRatio+$ratio"|bc`

Finally, the result is displayed
Image compression script

3 full script

github.