Replace JPEG libraries with MozJPEG
For an image heavy site we were building we needed to squeeze more bytes out of the JPEG files. We use Pillow within our Python project to create thumbnails which in turn uses the JPEG libraries installed on your system, so we had to look for a 1-on-1 replacement of the system jpeg libraries.
For Ubuntu you can use libjpeg-turbo but using MozJPEG by Mozilla makes the thumbnails even smaller. The only problem we ran into was the fact there is no repository you can add in Ubuntu and therefore we had to compile MozJPEG manually.
If you just want to skip the steps go to tl;dr. All the steps need to be ran as root.
Install requirements
To compile MozJPEG you need to install some requirements.
apt -y install build-essential cmake libtool autoconf automake m4 nasm pkg-config
and then configure the dynamic linker run-time bindings
ldconfig /usr/lib
Get MozJPEG source
We’ll be working with version 3.2 of the MozJPEG library.
wget https://github.com/mozilla/mozjpeg/archive/v3.2.tar.gz
tar xf v3.2.tar.gz
Configure and Install
Before we can configure and install we have to create the configuration. Go to the directory you extract the archive in.
cd mozjpeg-3.2
autoreconf -fiv
To keep source and build separate we’ll do the build in it’s own directory.
mkdir build
cd build
sh ../configure --with-jpeg8
make install libdir=/usr/lib/x86_64-linux-gnu prefix=/usr
We have to copy one source file over as it’s not included in the build.
cp ../jpegint.h /usr/include/jpegint.h
That’s it, now almost any program on your server that use the JPEG libraries to create images will be using MozJPEG and making the files much smaller than with the standard or even libjpeg-turbo libraries.
TL;DR
The script below will do all the above steps. Remember to run this as root.
#/bin/sh
apt -y install build-essential cmake libtool autoconf automake m4 nasm pkg-config
ldconfig /usr/lib
rm -rf mozjpeg-3.2
wget https://github.com/mozilla/mozjpeg/archive/v3.2.tar.gz
tar xf v3.2.tar.gz
cd mozjpeg-3.2
autoreconf -fiv
mkdir build
cd build
sh ../configure --with-jpeg8
make install libdir=/usr/lib/x86_64-linux-gnu prefix=/usr
cp ../jpegint.h /usr/include/jpegint.h
Bonus
If you use Pillow in your Python project and it was already installed you need to reinstall it, we ran into issues where after reinstalling it still would not use the MozJPEG libraries. In order to make that work, we had to recompile Pillow. The code below will recompile pillow
pip install --upgrade --no-cache-dir --force-reinstall --no-binary :all: --compile -v Pillow