Optimize images is one of the Google PageSpeed rule. JPEG and PNG files are most commonly used image format around the web. Compressed JPEG or PNG files has lower size than the original without loosing quality and helps speeding up your site. There are plenty different way to optimize and compress JPEG and PNG files for web. Some of the CMS has plugin to do the job. But, plugins takes time to compress all your files and slows down your site if you are using more plugins. There is an easy way to do this if you are using a Linux VPS or dedicated server and have a lot of images to optimize and compress. Follow the tutorial to know now and bookmark for future reference.
Requirements:
We will need the following 2 command line utilities to be installed in our server. They are very small in size and does their job properly. In this tutorial I’ll be bulk optimizing and compressing JPEG + PNG files in my Ubuntu 14.04 server using a Terminal window and a line of command for each file types.
- jpegoptim – Optimize and compress JPEG files
- OptiPNG – Optimize and compress PNG files
Installing the jpegoptim and OptiPNG
First of all, we need to install the utilities. Try not to use root
user to download and install the apps / utilities. A user with sudo
privilege is preferred. Run these if you don’t have the utilities already installed. If installed skip this step.
sudo apt-get update
#to update the sources list and repo
sudo apt-get install jpegoptim
sudo apt-get install optipng
Optimize and Compress JPEG Files
Open a terminal window. Browse to the specific folder or sub-folder location where you have all the JPEG files stored which needs to be optimized and compressed using the cd
command, then run the following command. It may take some time if you have loads of jpeg files.
sudo find . -type f -name "*.jpg" -exec jpegoptim {} \;
The above command will find all .jpg
files inside current folder and sub-folder(s) and will optimize them while preserving quality of the files.
Optimize and Compress PNG Files
Similarly, to optimize and compress PNG files, browse to the location of your PNG files and run the following command in terminal.
sudo find . -type f -name "*.png" -exec optipng {} \;
Compressing PNG files takes a bit longer than compressing JPEG files. But, the information remains intact in your PNG files, they don’t get removed.
Caution
The commands above with sudo
changes the file ownership to root:root
. You may notice that, optimized images are not displaying in your site, use the following command after you use jpegoptim and OptiPNG.
sudo chown -R www-data:www-data *
The command changes back the ownership recursively to www-data
, the right owner of the files and images now should be displaying on your site. I use them in my server every time I upload any image(s).
Imamiash says
Great! Can I do it on Ubuntu Desktop?!
Saddam Hossain says
Yes, Imamiash. You can use it on Ubuntu desktop.