Article by Ayo

The original link: https://freshman.tech/image-optimisation/

Images are one of the most basic types of content available on the Web. They say a picture is worth a thousand words, but it can be worth a few megabytes if you’re not careful.

So while Web images need to be crisp and crisp, they must also be presented in manageable sizes to keep load times small and data usage at acceptable levels.

On my website, I’ve noticed that my home page weighs over 1.1 MB and images make up 88% of it. I also realized that the images I provided were larger than they needed to be (in terms of resolution). Clearly, there is a lot of room for improvement.


After reading Addy Osmani’s excellent Essential Image Optimization ebook, I implemented his advice on my site. Then I did some research on the response image and applied it to my website.

This reduces the page weight to 445 KB. Page weight reduced by 62%


This article is about describing the steps I took to bring my home page weight to a more manageable level.

What is image compression?

To compress images is to reduce file size while maintaining an acceptable level of visual quality. To compress images on my site, Imagemin is my tool of choice.

To use Imagemin, make sure you have Node.js installed, then open a terminal window, CD into your project folder, and run the following command

npm install imagemin
Copy the code

Then create a new file, imagmin.js, and paste the following

const imagemin = require('imagemin');
const PNGImages = 'assets/images/*.png';
const JPEGImages = 'assets/images/*.jpg';
const output = 'build/images';
Copy the code

Feel free to change the PNGImages, JPEGImages, and output values to match your project structure.

To perform any compression, several plug-ins need to be introduced depending on the type of image to be compressed.

Compress JPEG with MozJPEG

To compress JPEG images, I used Mozilla’s MozJPEG tool, which is available as an Imagemin plug-in through Imagemin-Mozjpeg, which you can install by running the following command

npm install imagemin-mozjpeg
Copy the code

Then add the following to the imagmin.js file

const imageminMozjpeg = require('imagemin-mozjpeg');

const optimiseJPEGImages = (a)= >
  imagemin([JPEGImages], output, {
    plugins: [
 imageminMozjpeg({  quality: 70. }),  ]  });  optimiseJPEGImages()  .catch(error= > console.log(error)); Copy the code

You can run the script by running Node Imagemin.js on the terminal. This will process all JPEG images and place the optimized version in the Build/Images folder.

I’ve found that setting the quality to 70 produces a good enough image in most cases, but the effect can vary. You can experiment according to your own actual situation.

MozJPEG generates line-by-line JPeGs by default, which causes images to gradually load from low resolution to high resolution until the image is fully loaded. They also tend to be slightly smaller than baseline JPeGs because of how they are encoded.

You can use this nifty command-line tool from Sindre Sorhus to check if JPEG images are progressive.

Addy Osmani has detailed the advantages and disadvantages of using progressive JPEG. For me, I think the pros outweigh the cons, so I stick with the default Settings.

If you prefer to use a baseline JPEG, you can set progressive to false in the Options object. Also, be sure to visit the Imagemin-MozJPEG page to view the other Settings available.

PNG image optimization with PngQuant

Pngquant is my preferred tool for optimizing PNG images. You can use it with Imagemin-pngquant

npm install imagemin-pngquant
Copy the code

Add something to imagemin.js:

const imageminPngquant = require('imagemin-pngquant');

const optimisePNGImages = (a)= >
  imagemin([PNGImages], output, {
    plugins: [
 imageminPngquant({ quality: '65-80' }) ]. });  optimiseJPEGImages()  .then((a)= > optimisePNGImages())  .catch(error= > console.log(error)); Copy the code

I found that the quality parameter is 65-80, which provides a good balance between file size and image quality.

With these Settings, I was able to get a screenshot of a website ranging from 913 KB to 187KB without any noticeable loss of visual quality. A 79% drop!

Here is the same file. Take a look and judge for yourself

  • Original Image (913 KB)
  • Optimised Image (187 KB)

Provides services for browsers that support WebP images

WebP is a relatively new format from Google that aims to provide smaller file sizes by encoding images in lossless and lossy formats, making it an ideal alternative to JPEG and PNG.

WebP images can match the visual quality of JPEG and PNG images, but can greatly reduce the file size. For example, when I converted the screen capture to WebP from above, I got an 88 KB file, which was about the same quality as the original image at 913 KB. 90% reduction!

Look at all three images. Can you tell the difference?

  • Original PNG image (913 KB)
  • Optimised PNG image (187 KB)
  • WebP image (88 KB, can be viewed in Chrome or Opera)

Personally, I think the visual quality is comparable, and the cost savings are hard to ignore.

Now that we have identified the value of using the WebP format whenever possible, it is important to note that it is not a complete replacement for JPEG and PNG at this time, since WebP is not well supported by most browsers.

However, according to Caniuse.com, more than 70% of users worldwide use webP-enabled browsers. This means that by providing WebP images, you can make web browsing faster for about 70% of your customers.

Let’s take a look at the steps for putting WebP images on the network.

Convert your JPEG and PNG files to WebP

Converting JPEG and PNG images to WebP is very easy using the Imagemin-WebP plug-in.

Run the following command from your terminal to install it

npm install imagemin-webp
Copy the code

Add something to imagemin.js:

const imageminWebp = require('imagemin-webp');

const convertPNGToWebp = (a)= >
  imagemin([PNGImages], output, {
    use: [
 imageminWebp({  quality: 85. }),  ]  });  const convertJPGToWebp = (a)= >  imagemin([JPGImages], output, {  use: [  imageminWebp({  quality: 75. }),  ]  });  optimiseJPEGImages()  .then((a)= > optimisePNGImages())  .then((a)= > convertPNGToWebp())  .then((a)= > convertJPGToWebp())  .catch(error= > console.log(error)); Copy the code

I found that setting the quality parameter to 85 produced WebP images that were similar in quality to PNG images, but much smaller. For JPEG, I found that setting the quality parameter to 75 allowed me to find a good balance between visual quality and file size.

To be honest, I’m still experimenting with these values, so don’t take them as suggestions. And make sure you check the Imagemin-Webp page to see the other options available.

Use WebP images in HTML

Once you have WebP images, you can use the following tags to provide them to browsers that can use them, while providing the equivalent (optimized) JPEG or PNG fallback for those browsers that don’t support WebP.

<picture>
    <source srcset="sample_image.webp" type="image/webp">
    <source srcset="sample_image.jpg" type="image/jpg">
    <img src="sample_image.jpg" alt="">
</picture>
Copy the code

Using this tag, browsers that support the WebP media type will download WebP for transformation and display it, while other browsers will download the JPEG variant instead.

Any browser that doesn’t understand will skip alland load the content defined in the SRC attribute of the img tag at the bottom. As a result, we provide support for all types of browsers, gradually enhancing our pages.

Note that in all cases, the IMG tag is what is actually rendered on the page, so it really is a required part of the syntax. If you omit the IMG tag, no image is rendered.

The tag and all the sources defined in it are located here so that the browser can choose which image variants to use. Once the source image is selected, its url is fed to the IMG tag, which is what is displayed.

This means that you do not need to style the ortags because they are not rendered by the browser. Therefore, you can style just the IMG tag as before.

conclusion

As you can see, the process of optimizing images for use on the Web is not that complicated and can lead to a better user experience for customers by reducing page load times.