Using MozJPEG via Docker
Docker is great for deploying applications to container-based and cloud-based environments. It's also great for a quick install of utilities, with no worries about colliding library versions. Here's an example with a JPEG encoder library.
Join the DZone community and get the full member experience.
Join For Freemozjpeg , a jpeg encoder project from mozilla, is a fantastic way to optimize your jpeg files . setting it up however might be quite a hassle. fortunately, a virtualized environment such as docker offers a much simplified way to use mozjpeg.
the important requirement is that you have docker installed and ready to use. if you are on linux, this should be easy. for os x and windows users, follow the steps in my previous blog post on easy docker on os x .
first, we will grab mozjpeg source code :
git clone git://github.com/mozilla/mozjpeg.git
cd mozjpeg
git checkout v3.1
in the current directory, create a
dockerfile
with the following content. as you can see, here we will base it on
alpine linux
since it is quite small (around 5 mb).
from alpine:3.3
add . /source
run apk --update add autoconf automake build-base libtool nasm
run cd /source && autoreconf -fiv && ./configure --prefix=/usr && make install
once this
dockerfile
is ready, fire it up with:
docker build -t mozjpeg .

you can watch the progress as docker grabs alpine 3.3 base image and let alpine’s package manager,
apk
, install a number of dependent packages. after that, mozjpeg is being compiled and built from source. once this is completed (it may take a while), we are ready to utilize this new image for optimizing jpegs. also, there is no need to stay in the current directory.
for the basics on using mozjpeg, i recommend reading the article
using mozjpeg to create efficient jpegs
. let’s say we have a picture we want to optimize, e.g.
photo.jpg
. we can start a new docker container containing the above compiled mozjpeg and use it as follows:
cd ~/documents
docker run -v $pwd:/img mozjpeg sh -c "/opt/mozjpeg/bin/cjpeg -quality 80
/img/photo.jpg > /img/photo_small.jpg"
the command-line option
–v $pwd:/img
maps the current directory on your host machine to
/img
as seen from within the container. after that, a shell is invoked with the full command to start mozjpeg’s
cjpeg
at quality level 80. when i tried this on a simple photo, i was very happy with the optimized version while i got a massive decrease in file size (from 158 kb to 45 kb). of course, your mileage may vary and make sure you read kornel’s excellent article on
fair image comparison
.
still not optimizing your jpeg files? now you have no more excuse!
Published at DZone with permission of Ariya Hidayat, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments