Monday, August 27, 2012

Losslessly shrink JPEG images on a Mac

This is a tutorial on compiling and using a unix utility called jpegoptim. jpegoptim is a program used to shrink jpeg images without losing quality. jpegoptim optimizes the encoding without resorting to lossy re-compression.

To get started, you need a Mac with Xcode installed. You will also need the gcc compiler. Older versions included this but newer versions require a separate install.

You will need to download two packages of source code. The first is jpegoptim at http://www.kokkonen.net/tjko/projects.html
Scroll down on the page to jpegoptim section. I am using "jpegoptim v1.2.4". Click on the "[source]" link to download.

The next package is the jpeg library. You can download it at http://www.ijg.org. Look for the link: jpegsrc.v8d.tar.gz

Once you have them downloaded open the Terminal application and enter the following:

cd Downloads/
tar zxvf jpegsrc.v8d.tar
cd jpeg-8d/
./configure
make
make install
sudo make install
cd ../jpegoptim-1.2.4
./configure
make
sudo make install
jpegoptim --help

To shrink a jpeg file, run jpegoptim <filename.jpg>

You can also shrink a lot of jpeg files by running a command like this:

find ./ -iname '*.jpg' -exec jpegoptim -p {} \;

This will optimize jpeg images in the current directory including recursing into subdirectories. The "-p" flag keeps jpegoptim from updating the timestamp.

Notes:
Use at your own risk. Please back up your files before using this. I have never had jpegoptim cause me problems but it is not worth taking any chances. If it can't optimize an image, it just ignores it. I have found that I can run jpegoptim on any file type (like a .doc file) an it will just give an error without hurting the file.

If you are using backup software like Time Machine, optimizing jpeg images will cause the files to change and thus the Time Machine software will back them up again. This can result in having to backup a lot of files.

I have had differing results with jpegoptim. I found images from an old digital camera consistently shrinking by 20%. With a newer camera I have, the images typically shrink around 3-4%. You can usually test it on a few files from a specific source and get a rough idea of how much it will optimize the images from that source.

If you have any suggestions or questions, please post them in the comments. If you like this article, please subscribe as I may post similar articles in the future.