Top

How to Bulk Optimize JPG and PNG Images on Ubuntu

While there are lots of WordPress plugins that compress image files, they’re mostly paid, or worse, based on a never ending subscription fee. Setting up open-source native image compression on a Linux server is actually surprisingly easy to do and the best part is, it’s free. If you have root access to your Ubuntu server, setting up PNG and JPG compression is super easy and should give you significantly better scores on tools like Google’s Page Speed Insights.

First, install JPEGOptim and OptiPNG:

sudo apt-get install jpegoptim
sudo apt-get install optipng

Now that we’ve got JPEGOptim and OptiPNG installed (pretty hard, huh?) we need to open the parent directory that all of the images we want to optimize live in or under. In this case, I’m optimizing the images in a WordPress 4.9.5 instance, so I’m going to CD to the “WP-Content” folder:

cd /var/www/ayrne.com/htdocs/wp-content

Now that I’m in the WP-Content folder, I can compress all of the images that live in this folder, as well as all of the other files that are contained in the sub-folders below it:

find / -name "*.png" -exec optipng '{}' \;
find / -name "*.jpg" -exec jpegoptim '{}' \;

 

We could change this just a bit so that the script will search everything instead of just the current directory

 

Well that was easy, wasn’t it? If you want to go one step further and make your JPGs even more optimized, you could use this instead of the first script:

for x in $(find $PWD -iname "*.jpg"); do jpegoptim --all-progressive $x; done

Progressive optimization will allow requests to be made while JPGs are still loading (versus each JPG having to load in sequence before the next request can begin).

Lastly, if you’re feeling extra specially ambitious, you can run this script which strips all meta data associated with images, compresses them, and optimizes them to be progressive:

optimize() {
  jpegoptim *.jpg --strip-all --all-progressive
  for i in *
  do
    if test -d $i
    then
      cd $i
      echo $i
      optimize
      cd ..
    fi
  done
  echo
}
optimize

Here’s that same script modified for OptiPng:

optimize() {
  optipng *.png
  for i in *
  do
    if test -d $i
    then
      cd $i
      echo $i
      optimize
      cd ..
    fi
  done
  echo
}
optimize

Now, let’s make it even better by combining them:

optimize() {
  jpegoptim *.jpg --strip-all --all-progressive
  optipng *.png
  for i in *
  do
    if test -d $i
    then
      cd $i
      echo $i
      optimize
      cd ..
    fi
  done
  echo
}
optimize

I'm an artist, traveler and lover of the beauty in life. I also built this website and have contributed some pretty awesome articles to it.

Post a Comment

Previous Next
Close
Test Caption
Test Description goes like this