Image Optimization-Quick Script

Posted by JD 03/24/2016 at 19:01

When sharing images or publishing them to a website, reducing the file size, especially when a human cannot tell the difference, is smart for many reasons.

Convert is part of the ImageMagick package which has been around for decades.

$ more img-opt
#!/bin/bash
QUAL=40   # 40 is safe. 20 often works too for even smaller files

for img in "$@"; do
  NEW=${img/%.???/-opt.jpg}
  echo " Working on $img ..."
   /usr/bin/convert -quality $QUAL  "$img"  "$NEW"
done
# Rename ... perhaps.
echo "rename 's/-opt.jpg/.jpg/g' "

Don’t forget to chmod +x img-opt after creating the file. I’d place it in either /usr/local/bin or ~/bin/ .

Rename is part of perl and amazing, but I prefer to wait until I’ve manually reviewed the results most of the time.
Input files and globbing by the shell dictate that filenames cannot have spaces. I’m lazy and it is really easy for me to prevent spaces in filenames, so this and all other scripts I create make that assumption.

Typical use is:
$ img-opt D*g

This will glob all the files beginning and ending with D/g and run the convert/optimization on each in turn. New files ending in -opt.jpg will be the result – even if files already have that name, those characters will be replaced. Safety.

Other image file types can be input, but only jpg output is possible.

I’ll work in a temporary directory, with copies of the original image files. Then I use an image viewer to quickly look through all the files and delete the originals. If everything looks good, I’ll rename all the files en-mas, before pushing them to a web site or adding to an email attachment.

This script shows some simple techniques to run the same process over a bunch of files using input file globbing. That is extremely powerful. The input list of files can come from anywhere:

  1. the shell, using globbing
  2. a file with a list of files
  3. another command like ‘find’
  4. pipes …

Very powerful.

Be aware that globbing on Unix systems is VERY different from globbing on Windows. The *.* stuff on Windows is never needed on Unix. Extensions don’t matter on Unix.