Lossless compression of images using OptiPNG and jpegoptim to reduce ECS space usage
Created#More Posted time:Mar 3, 2017 16:39 PM
Images have always been a big user of storage space and data for websites, as evidenced by the migration process - you may be simply stunned at how quickly image libraries grow to be several hundred gigabytes. Fortunately we have image compression technologies to relieve the situation, and dozens of gigabytes of space may be spared.
It is too effort-consuming to drag the image libraries out and compress the images one by one. In Linux systems, we can just run a command and make ourselves a cup of coffee, waiting for the compression to complete on its own.
OptiPNG is a lossless compression tool for PNG images. It can also convert non-PNG files (BMP, GIF, PNM and TIFF) into compressed PNG files.
Jpegoptim is a tool used to optimize JPEG files. It provides lossless optimization (based on Huffman Table) and lossy optimization implemented by quality factors.
yum install optipng jpegoptim
apt-get install optipng jpegoptim
brew install optipng jpegoptim
Suppose the physical path of our website is: /home/mf8/mf8.biz/public_html
Enter the website directory
find . -iname '*.png' -print0 | xargs -0 optipng -o7 -preserve
All the PNG files under all directories, including the sub-directories will be compressed. But because the tool will select the best solution after comparing several options for the compression, a very long time is required. I spent two hours compressing 100MB of images.
find . -iname '*.jpg' -print0 | xargs -0 jpegoptim --strip-all --preserve --totals --all-progressive
The speed will be much faster for compressing the same size JPG files. The –max=90 parameter is added to customize the size of the lossy compression. For example, here 90% lossy compression is provided to improve the compression efficiency.
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
Enter the above code and all the PNG and JPG files under the /var/www directory will be compressed at 02:00, and a directory will be generated under the /root directory.
The compression operation consumes a lot of CPU resources, sometimes close to 100%. We recommend you perform compression when there are few visitors and not to use the software on machines with a shared core. Otherwise your account will surely be suspended due to occupying too much CPU resources.