How to Optimize and Compress images automatically in Linux

In this tutorial, I will show you how to compress pictures by using jpegoptim, pngquant, and inotifywait from a folder that gets updated. Check this tutorial on how to install the required programs:

Let’s get started.

First, we need to create the bash script:

touch test.sh && vim test.sh

Now we add the directory we want to watch:


#!/bin/bash
DIRECTORY_TO_OBSERVE="/your_directory/location"

Change “/your_directory/location” with the folder location you want to watch.

Next, we need to define two commands for optimizing jpg files and png files:

jpgcompress(){
jpegoptim -p --strip-all --all-progressive -m75 "$1"
}
pngcompress(){
pngquant -f --ext .png --quality=65-80 "$1"
}

Here you need to change those values “-m75” and “–quality=65-80” with the quality you want for your pictures.

Next, we create the actual command that will check what is the extension of the picture and run the appropriate command based on the extension we find, so in case the extension is jpg will run the jpegoptim command, and if the extension is png, will run the pngquant command:

compress(){
filename=$(basename "$1")
extension="${filename#*.}"


if [ ${extension} == jpg ]
  then
   jpgcompress "$1"
elif [ ${extension} == png ]
  then
   pngcompress "$1"
fi
}

Next, we need to use the inotifywait command to watch the directory for new files that get created

inotifywait -mrq -e create --format %w%f $DIRECTORY_TO_OBSERVE | while read FILE; do compress "$FILE"; done

Here is the entire script:

#!/bin/bash
DIRECTORY_TO_OBSERVE="/your_directory/location"

jpgcompress(){
jpegoptim -p --strip-all --all-progressive -m75 "$1"
}
pngcompress(){
pngquant -f --ext .png --quality=65-80 "$1"
}
compress(){
filename=$(basename "$1")
extension="${filename#*.}"

if [ ${extension} == jpg ]
  then
   jpgcompress "$1"
elif [ ${extension} == png ]
  then
   pngcompress "$1"
fi
}
inotifywait -mrq -e create --format %w%f $DIRECTORY_TO_OBSERVE | while read FILE; do compress "$FILE"; done

Before running this script, we need to make it executable by running the next command:

chmod +x test.sh

Now you can run the command, but I suggest you first test it before running it on production.

./test.sh

Leave a Reply

Your email address will not be published.