Before I wrote an article: JPG, GIF, PNG and SVG for the Web, we should choose the most appropriate image format, introduced the characteristics of these image formats, and how to choose the right image for the website, then a big guy in the comments section asked me to add WebP format, and it came.

What is WebP format

WebP is a modern image format that provides excellent lossless and lossy compression for images on the Web. Using WebP, webmasters and Web developers can create smaller, richer images that make the Web faster.

WebP lossless images are 26% smaller than PNG. WebP lossy images are 25-34% smaller than comparable JPEG images under the same SSIM quality index.

Lossless WebP supports transparency (also known as Alpha channels) while increasing the number of bytes by only 22%. For cases where lossy RGB compression is acceptable, lossy WebP also supports transparency, and file sizes are typically 3 times smaller than PNG.

The above three passage from developers.google.com/speed/webp

Why do you need this format

Because WebP images are smaller than JPEG and PNG images – typically a 25-35% reduction in file size. This reduces page size and improves performance. Here are two examples:

  • YouTube found that switching to WebP thumbnails increased page loading by 10%.
  • When they switched to WebP, Facebook saved 25-35% in JPEG file sizes and 80% in PNG file sizes.

WebP is an ideal alternative to JPEG, PNG, and GIF images. In addition, WebP provides lossless and lossy compression. In lossless compression, no data is lost. Lossy compression reduces file size at the expense of image quality.

How do I convert images to WebP format

Typically, developers convert images to WebP format in one of two ways:

  • Cwebp command line tool
  • Imagemin WebP plugin (NPM package)

If your project is simple or you only need to convert images once, the CwebP command line tool is a good choice. If you use a build tool such as Webpack or Gulp to build your project, then transferring images to WebP using the Imagemin WebP plugin is your best bet.

There are many parameters you can set when converting an image to WebP format, but the only thing you need to care about is compression quality. You can specify a compression quality level, which ranges from 0 to 100, with 0 being the worst and 100 being the best. So what is the best setting for it? So it’s going to take a little bit of practice to figure out which quality level is going to be good without making the file too big?

Convert images using CWEBP

To use this command, you need to install the webp tool package and perform the following steps:

  • You can download the webP package here. This website provides many versions of the package. Choose a package that is compatible with your computer, for example, I am a Mac OS. Then put the unzipped folder in the directory you want to save it in. I put it in /Applications/Utilities/.

  • Set environment variables so that the command can be used on the terminal. /Users/ CCP /.bash_profile: /Users/ CCP /.bash_profile:

    The export PATH = $PATH: / Applications/Utilities/libwebp - 1.1.0 - rc2 - MAC - 10.15 / binCopy the code

    To make the command take effect immediately after the modification, run source. bash_profile on the terminal

  • You can then type cwebp in the terminal, and if it tells you how to use the command, the package is installed and you can use the cwebp command normally.

  • The libwebp READMD package provides many additional commands in addition to the cwebp command. For details, see the documentation.

In addition to this slightly troublesome installation method, you can also use OS X package management tool to install (why didn’t you say 😭) :

  • Homebrew WebP package
  • Macports WebP package

Once the installation is successful, you can happily use the cwebp command. Take a look at the following operations:

Convert a single image using cwebP’s default compression Settings (default is lossy compression, and default compression quality parameter is 75) :

cwebp images/flower.jpg -o images/flower.webp
Copy the code

Use 50 quality levels to convert individual images:

cwebp -q 50 images/flower.jpg -o images/flower.webp
Copy the code

Convert all files in the specified directory:

for file in images/*; do cwebp "$file" -o "${file%.*}.webp"; done
Copy the code

Use Imagemin to convert images

The Imagemin Webp plug-in can be used independently in the Node environment or in conjunction with build tools such as Webpack. It usually only takes about 10 lines of code to configure.

In Node, the following code converts images from the images directory to WebP images and stores them in the compressed_images directory:

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

imagemin(['images/*'] and {destination: 'compressed_images'.plugins: [imageminWebp({quality: 50})]
}).then(() = > {
    console.log('Done! ');
});
Copy the code

In the build tool Webpack used, here also with the copy-webpack-plugin to achieve the copy of the picture. The following code comes from webp-webpack:

// Copyright 2018 Google LLC.
/ / SPDX - License - Identifier: Apache 2.0

const ImageminWebP = require('imagemin-webp');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');

module.exports = {
    entry: './index.js'.output: {
        filename: 'bundle.js'.path: path.resolve(__dirname, 'dist')},plugins: [
        new CopyWebpackPlugin([{
            from: './images/**/**'.to: './images/[name].webp'
        }]),
        new ImageminPlugin({
            // imagemin-webp docs: https://github.com/imagemin/imagemin-webp
            plugins: [ImageminWebP({quality: 50]})]}})Copy the code

You can also try using the Imagemin-webp-webpack-plugin, as I see it has been updated in the last 4 months and is getting close to 10K downloads, which should do the job.

Compare WebP with other image formats

Here I made a picture with Photoshop:

Then I used it to export 4 images, their information is as follows:

  • jpg_60.jpg: 60 quality JPG image, 48KB;
  • jpg_100.jpg: quality 100 JPG image, 142KB;
  • png_8.png: 8-bit PNG image, 60KB;
  • png_24.png: 24-bit PNG image, 200KB;

Then I used the following command to batch convert them into WebP images:

for file in Downloads/img/*; do cwebp "$file" -o "${file%.*}.webp"; done
Copy the code

You can then see the following information for all the files under your Downloads/img/ folder:

It is found that the file sizes of these 4 images are almost the same after they are converted into WebP format images, which are about 22KB, much smaller than the original, especially the size reduction of PNG 24 and JPG 100 images is more obvious. The worst JPG quality, 60, was reduced by 54% when converted to WebP format.

Next, we can use the online tool TinyPNG to compress these 4 images. Here is the information after the file is compressed (the left and right columns of green numbers respectively indicate the size before and after the file is compressed) :

It is found that TinyPNG has a better compression effect on PNG 24 and JPG 100 images. In addition, comparing the compressed 4 images with WebP images (22KB), we found that the file size of WebP images is still significantly smaller, more than 50% smaller, so this is why we recommend using WebP images in Web applications, it is really optimized too large.

Lets WebP images preview properly on Mac

As you can see from the second image above, WebP images do not preview properly on the Mac, so you need to add this capability to the Mac. Also need to say that WebP images in Chrome can be very good support, directly drag the image into the browser to display.

Speaking of previews, take a look at WebP compatibility across browsers:

As you can see from the figure above, WebP images are pretty well supported by modern browsers, so there’s no problem using them in a production environment.

Mac needs to preview WebP images properly, and there are two plugins qlImageSize has downloaded to support it:

  • qlImageSize:QuickLookPlugin, used to preview WebP images, and can display size, file size and other information in the title bar, in addition to WebP images in the form of thumbnail display.
  • mdImageSize:SpotlightPlugins that support WebP image information when displaying profiles;

After downloading the two plug-in packages, unpack them and copy the plug-in to the corresponding directory for saving:

  • qlImageSizeCopied to the/Library/QuickLookDirectory;
  • mdImageSizeCopied to the/Library/SpotlightDirectory;

At this point, WebP images should be quickly previewed, if not, restart the access process (hold down Option, right-click access, and select Restart).

Compatible with different browsers

If your site needs a browser that doesn’t support WebP images (IE11, for example), there is a solution that will prevent images from displaying incorrectly due to browser compatibility:

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

For this code, the browser will first check to see if it supports resources in thetag list, and load flower.webp images by default if they are compatible. If none of the resources in thelist are supported, it will load the images specified in .

What to do next

The images in my previous project were mostly in JPG\PNG format. I found a Banner image of our homepage, which was 1920px wide. After being compressed by the compression tool, the file size was still 275 KB. When I use the CWebP tool to convert the -q 75 quality parameter to a WebP image, do you know what its file size becomes? It becomes 50KB 😱

Really don’t try don’t know, a try surprised, the original WebP format pictures can bring so much optimization effect, the most critical is that 2 pictures with the naked eye look similar display effect.

Really great 👍, WebP single-handedly improves the performance of the site to a higher level. So now we have the KPI: we can happily turn all the images in the project into WebP images. After this, you can raise your salary with the leader. The leader led me to optimize our website, and the performance has been improved by about 10% ~ 20%. But what happens next, don’t come to me.

Refer to the article

  • Web. Dev/serve – image…
  • developers.google.com/speed/webp
  • Github.com/Nyx0uf/qlIm…