Hi, I'm Rodo 👋

I'm a Software Engineer

Rodolfo Guluarte Hale

Hi, I'm Rodo 👋

I'm a Software Engineer

Script to speed up your website with image compression

2 minutes
May 1, 2023

Websites with heavy images can take longer to load, which may affect user experience and SEO. To tackle this issue, I decided to create a small script to compress and optimize the images for my website.

To get started, I first installed the necessary tools. I used optipng, pngcrush, and jpegoptim for image compression, and advpng-bin for additional optimization:

sudo apt-get install -y optipng pngcrush jpegoptim
npm install --save advpng-bin -g

Next, I created a shell script called optimize-img.sh with the following content:

cd ./img-dir/
find . -type f -iname "*.webp" -exec optipng -nb -nc {} \;
find . -type f -iname "*.webp" -exec advpng -z4 {} \;
find . -type f -iname "*.webp" -exec pngcrush -rem gAMA -rem alla -rem cHRM -rem iCCP -rem sRGB -rem time -ow {} \;
find . -type f \( -iname "*.webp" -o -iname "*.webp" \) -exec jpegoptim -f --strip-all {} \;

This script first changes the directory to ./img-dir/, where all the images are stored. Then, it compresses and optimizes PNG images with optipng, advpng, and pngcrush. Finally, it compresses and removes metadata from JPG and JPEG images using jpegoptim.

To make the script executable, run:

chmod +x ./optimize-img.sh

To compress and optimize the images, simply run the script:

./optimize-img.sh

Moreover, the real power of this script can be harnessed by integrating it into your Continuous Integration/Continuous Deployment (CI/CD) pipeline. By automating the image optimization process, you can ensure that every new image added to your website is compressed and optimized before deployment. This eliminates the need to manually run the script each time you update your website’s content.

To include the script in your CI/CD pipeline, simply add the script execution step to your pipeline configuration. For example, if you are using GitHub Actions, you can create a new job that runs the optimize-img.sh script before deploying your website. This way, the optimized images are pushed to your production environment, ensuring that your website remains fast-loading and efficient for all visitors. The integration of this script into your CI/CD pipeline not only saves time but also helps maintain a high-quality user experience on your website.

The script reduced the size of my images significantly, which resulted in a faster-loading website. This simple solution can help improve both user experience and SEO rankings. I hope this guide helps you optimize images on your website too!