Optimizing JPEG images with MozJPEG
MozJPEG is a project from Mozilla aimed to improve JPEG compression while keeping full backwards compatibility with current decoders. Recently they released version 3 of the library. Previous version reduced files by 5% on average compared to jpeg-turbo, the JPG compression library it is based on. The new version contains more improvements, such as reducing compression artifacts for text on white background, and better quality for high-resolution images.
Installing and using MozJPEG in OS XMozJPEG can be installed on a Mac via Homebrew package manager by typing:
Since mozjpeg is a replacement for libjpeg, to avoid any compatibility issues with programs using libjpeg or its utilities, Homebrew won't create symlinks to replace libjpeg with it. For convenience, I created the following links to cjpeg and jpegtran binaries from mozjpeg:
brew install mozjpeg
(Note: replace 3.0 with whatever version you have installed, e.g. 3.1)
This way calling
ln -s /usr/local/Cellar/mozjpeg/3.0/bin/cjpeg /usr/local/bin/mozcjpeg
ln -s /usr/local/Cellar/mozjpeg/3.0/bin/jpegtran /usr/local/bin/mozjpegtran
cjpeg will execute the libjpeg's utility, while calling
mozcjpeg will use the Mozilla's version. All following examples will use binaries linked like this.
Converting PNG to JPEG with MozJPEGTo convert PNG to JPG, we'll first use
convert utility from ImageMagick (you probably have it installed; if not, run
brew install imagemagick) to convert PNG to a format accepted by
cjpeg, and then pipe the result of conversion into MozJPEG's version of
cjpeg to get the JPEG file:
Tweak quality parameter (recommended range is 50 to 90) until you get the results you need.
convert filename.png pnm:- | mozcjpeg -quality 90 > filename.jpg
Optimizing and re-compressing JPEGsIf you want to make your JPEGs smaller with MozJPEG optimizer, you can use
jpegtran utility from its distribution:
(again, we're using
mozjpegtran -outfile output.jpg -optimise -copy none input.jpg
mozjpegtran which is symlinked to
jpegtran binary from mozjpeg, see above.)
JPEGtran uses lossless optimizations, so there will be no change in quality. If you'd like to re-compress JPEGs, losing some quality, but making it even smaller, you can again use
convert utility with
Again, tweak quality option for your taste.
convert filename.jpg pnm:- | mozcjpeg -quality 70 > filename-optimized.jpg