Lossless Image Compression with OptiPNG and jpegoptim
Introduction
Images are a major consumer of storage and bandwidth on websites. This becomes especially apparent during migrations, where hundreds of gigabytes of image libraries can be overwhelming. Fortunately, image compression technology can help recover significant space—potentially saving tens of gigabytes.
Manually compressing each image in a library is inefficient. On Linux systems, you can automate the process with a single command and enjoy the results while you take a coffee break.
Overview
OptiPNG is a tool for lossless compression of PNG files. It can also convert non-PNG files (BMP, GIF, PNM, and TIFF) into optimized PNG format.
jpegoptim is a tool for optimizing JPEG files. It provides lossless optimization based on Huffman tables and also supports lossy optimization by setting quality factors.
Installation
RHEL, CentOS
yum install optipng jpegoptim
Debian, Ubuntu
apt-get install optipng jpegoptim
macOS
brew install optipng jpegoptim
Usage
Assume the physical path of your website is: /home/mf8/mf8.biz/public_html
Navigate to the website directory
cd /home/mf8/mf8.biz/public_html
Compress PNG files
find . -iname '*.png' -print0 | xargs -0 optipng -o7 -preserve
This command compresses all PNG files in the current directory and all subdirectories. However, since OptiPNG evaluates multiple compression strategies to find the best one, the process can be very time-consuming. For example, compressing a 100MB image took two hours in one case.
Compress JPG files
find . -iname '*.jpg' -print0 | xargs -0 jpegoptim --strip-all --preserve --totals --all-progressive
This compresses all JPG files similarly but is much faster. You can add the --max=90 parameter to enable lossy compression at 90% quality, improving compression efficiency.
Advanced Usage
To automate the process, add the following cron job:
10 2 * * * echo `date` >> /root/optipng.log && find /var/www/ -mtime -2 -iname '*.png' -print0 | xargs -0 optipng -o7 -log /root/optipng.log -preserve && echo `date` >> /root/jpegoptim.log && find /var/www/ -mtime -2 -iname '*.jpg' -print0 | xargs -0 jpegoptim --max=90 --preserve --totals --all-progressive >> /root/jpegoptim.log
This script runs at 2:00 AM daily, compressing PNG and JPG files modified within the last two days in /var/www/, and logs the results to /root/optipng.log and /root/jpegoptim.log.
Important Notes
Image compression is extremely CPU-intensive, often consuming nearly 100% of CPU resources. It is recommended to run compression during periods of low visitor traffic. Do not use these tools on shared hosting environments, as high CPU usage may lead to account suspension.
To mitigate this, you can use cpulimit to restrict the CPU usage of compression tools. For more information, see: How to Limit CPU Usage with cpulimit