Table of Contents
This article I will introduce to you a script that automatically optimize image with mozjpeg.
For those of you who don’t know about MozJPEG, this is a great photo optimizer tool from Mozilla. It is capable of compressing images very costly and still retains the image quality.
Script automatically optimize image
I wrote the script and put it on my gitlab repository. You can use the following command to download it to your computer.
wget https://gitlab.com/Danny_Pham/WriteBash.com/raw/master/Utilities/07-Script_automatically_optimize_image_mozjpeg.sh -O optimize_image.shOr you can copy the script contents directly below and save the file optimize_image.sh.
#!/bin/bash
# Script author: Daniel Pham
# Script site: https://devopslite.com
# Script date: 19-03-2019
# Script ver: 1.0
# Script automatically optimize images with tool MozJPEG.
# Function optimize images
f_optimize () {
# Create folder 'image' to save optimized images
mkdir image
# List all .jpg file in current folder
ls | grep jpg > list.txt
# Read file list.txt and optimize each image
while read -r line
do
/usr/bin/mozjpeg -optimize -quality 80 "$line" > image/"$line"
done < list.txt
# Remove file list.txt after finish optimize
rm -f list.txt
}
# Main function
f_main () {
f_optimize
}
f_main
# Exit script
exitExplain my script
Recommended Reading: Script file location and execute script
Step 1: The script will create the image folder used to save the optimized images.
mkdir imageStep 2: List all JPG files in the current directory and save them as a list file.
ls | grep jpg > list.txtAnd step 3: Use the mozjpeg command to optimize images.
while read -r line
do
/usr/bin/mozjpeg -optimize -quality 80 "$line" > image/"$line"
done < list.txtUse script
To use the script, follow the instructions below.
1. Download the script to your computer, name it optimize_image.sh.
2. Put the script into the folder containing the .jpg image. For example, my photo folder is /Desktop/shutter.
3. Run the following command to execute the script.
$ bash optimize_image.shExample of using a script to optimize image

For example, in the shutter folder, there are 2 jpeg images of the following size.
104K Selection_001.jpg
116K Selection_002.jpgThen I put the script into the folder shutter, opened the terminal and ran the execute command.
bash optimize_image.shAnd this is the result of the optimized image size.
24K image/Selection_001.jpg
28K image/Selection_002.jpgConclusion
Mozjpeg is a great free tool for optimizing your photos. There is no problem when you optimize several images, but imagine if you have 1000 or even tens of thousands of photos. What you will do?
Now, this script will help you solve that problem very quickly. Hope it useful for you.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).