Batch JPG/PNG Image Compression and Optimization via SSH

This setup will compress all JPG and PNG images in below directories automatically.

  • /public_html/product_images/
  • /public_html/images/
  • /public_html/templates/

Prerequisite

Make sure below 2 packages are available in your server:

  • jpegoptim
  • optipng
yum install epel-release
yum install jpegoptim
yum install optipng

Implementation

Create file img-opt.sh under cPanel account directory

Add the following bash script to the file and save the file, where accname variable should be changed to your actual account name

View Post

#!/bin/bash

accname=moddiy

find /home/$accname/public_html/product_images/ -name *.jpg -exec jpegoptim -m90 -s --all-progressive --force '{}' \;
find /home/$accname/public_html/product_images/ -name *.png -exec optipng -o2 -strip all -preserve '{}' \;

find /home/$accname/public_html/images/ -name *.jpg -exec jpegoptim -m90 -s --all-progressive --force '{}' \;
find /home/$accname/public_html/images/ -name *.png -exec optipng -o2 -strip all -preserve '{}' \;

find /home/$accname/public_html/templates/ -name *.jpg -exec jpegoptim -m90 -s --all-progressive --force '{}' \;
find /home/$accname/public_html/templates/ -name *.png -exec optipng -o2 -strip all -preserve '{}' \;

find /home/$accname/public_html/product_images/ -type f -name '*.bak' -delete
find /home/$accname/public_html/images/ -type f -name '*.bak' -delete
find /home/$accname/public_html/templates/ -type f -name '*.bak' -delete

Run below command via SSH manually

bash /home/moddiy/img-opt.sh

Or, setup a cron job to run this script regularly automatically

/bin/sh /home/moddiy/img-opt.sh

Leave a Reply

Your email address will not be published. Required fields are marked *