Pictures can be seen everywhere in every major website, because the expression of pictures is more intuitive than words, so pictures are one of the most important elements of a website. Images are very large compared to other files, and the loading speed of the page is largely determined by the loading speed of images, so we need to optimize images to speed up the page loading speed and improve the user experience.

Image optimization can be divided into two aspects: image selection and use, loading and display. This article mainly discusses the selection and use of images to optimize performance, the next article will introduce image loading optimization.

1. Image basics

The basic idea of image resource optimization can be summed up in two words: compression. Whether it is the file format of the selected image, or the compression to a smaller size for the agreed format, its essence is to complete the transmission and display of images with less resource overhead.

In web pages, if it is determined that the display effect of images must exist, it is not necessary to use image files in the front-end implementation. There are also some scenes that can be used in a more efficient way to achieve the desired effect, such as the following situations:

  • Image in different states will not have the display effect (such as corner cutting, shadow, gradient, etc.), if you can use CSS to deal with the real effect, you can use CSS to achieve, CSS code relative to the picture, is negligible;
  • If there is some text on the image, if possible, use the text of the web page instead, as the text in the image contains a lot of information, resulting in a large image. In addition, the text in the image can be a poor user experience (unable to select, search, zoom, etc.) and will not look as good on a high-resolution screen.

With these two examples out of the way, let’s look at the basics of image correlation.

(1) Vector map and bitmap

Image files can be divided into vector and bitmap, let’s take a look at the differences between the two types of image.

1) Vector graph The following is the definition of vector graph in Baidu Encyclopedia:

A vector graph, also known as an object-oriented image or graphic image, is mathematically defined as a series of lines connected by points. Graphic elements in a vector file are called objects. Each object is a self-contained entity with properties such as color, shape, outline, size, and screen position.

Vector map is suitable for simple geometric shapes such as text, LOGO, control icon, two-dimensional code and so on.

The advantages of vector diagrams are as follows:

  • The file is small, the image is saved in the line and block information, so the vector graphics file has nothing to do with resolution and image size, only with the complexity of the image, image file storage space is small.
  • The image can be scaled infinitely, and the image will not produce a sawtooth effect when it is scaled, rotated or deformed.
  • Available for high resolution printing, vector graphics files can be printed on any output device printer at the highest resolution of printing or printing.

Of course, vector images also have their drawbacks: they are not rich in detail, and for very complex images, the image may be large to achieve the desired effect.

SVG is an IMAGE format based on XML, and its whole process is Scalable Vector Graphics (SVG), which is a TWO-DIMENSIONAL Vector Graphics standard based on XML launched by W3C. SVG can provide high-quality rendering of vector graphics, and SVG graphics are often interactive due to their support for JavaScript and the document object model. SVG, on the other hand, is a W3C recommended XML-based open standard that integrates seamlessly with other web technologies.

Currently, almost all browsers support SVG, and many ICONS on iconFont are in SVG:SVG tag contains part is all the content of the vector graph, in addition to the necessary drawing information and may include some metadata, such as XML namespaces, layer and annotation information, etc., but the information is not important for browser rendering SVG, so before use, can use the tool to the metadata to achieve the purpose of compression.

2) Bitmap A bitmap, also known as a lattice image or raster image, is made up of single points called pixels (picture elements). These points can be arranged and dyed differently to form a pattern. The more raster pixels that make up the image and the wider the color range that each pixel can represent, the more realistic the display effect of bitmap image will be. Most of the commonly used pictures belong to bitmap.

While bitmaps don’t have the resolution-independent quality of vector graphics, they can provide a more realistic experience of detail for complex images.

When we enlarge the bitmap, we can see the countless individual squares that constitute the whole image, and each pixel block stores the color information of the image. The color coding of the bitmap is mainly in the following two ways:

  • RGB: A color is represented by the optical intensity of the red, green and blue primary colors. This is the most common bitmap encoding method and can be used directly for screen display.
  • CMYK: use cyan, magenta, yellow and black pigment content to indicate a color. One of the commonly used bitmap coding methods that can be used directly for color printing.

Typically, browsers allocate one byte of storage for each color channel, which is 28=256 color levels. The size of an image is proportional to the number of pixels it contains. The more pixels an image contains, the more details it can display, the richer the details it can display, and the larger the image. For performance reasons, images must be compressed when used.

(2) Resolution

When we write CSS, we often set the length pixel value for the image to be displayed. However, on different device screens, sometimes the same image and position, the display effect may be quite different. The main reason for this difference is that there are two different resolutions: screen resolution and image resolution.

  • Image resolution: Represents the actual pixel value information contained in the image file. For example, an image with a resolution of 100 x 100 pixels defines a message of 100 pixels in length and 100 pixels in width.
  • Image resolution: represents the maximum pixel value that the display device can display, for example, the resolution of a computer is 2560 * 1600 pixels;

Both resolutions use pixels, so what’s the difference? In fact, a 100 x 100 pixel image can be displayed on a 200 x 200 pixel screen as well as a 400 x 400 pixel screen. On higher-resolution devices, it helps to display more colorful images, which is actually good for vector images because it doesn’t distort due to magnification. For bitmap, only when the image file contains more information, can make full use of the screen resolution, if the high resolution display screen to display the image information is not too much bitmap pictures, it will be distorted to a certain extent.

To display images at different resolutions, the tag and its SRcset attribute can be used to provide variations of the image, which can be used to provide image files at different resolutions for different devices:

<img src="dog.png"
     alt="A picture of a dog"
     srcset="dog-2.png 2x,dog-3.png 3x,dog-4.png 4x">
Copy the code

The srcset attribute is supported by most browsers. The browser will parse it before making a request and only select the most suitable image file for download. If the browser does not support the srcset attribute, you need to add the default loaded image to the SRC attribute.

(3) lossy and lossless compression

Compression is an important way to reduce resource source file size, for the image file, due to the sensitivity of the human eye to different color is different, so can reduce a certain color coding way to reduce the size of the file, you can even lose part of the source file information, in order to achieve the result of approximate, compressed file size will be smaller.

So for image compression, should use lossy compression or lossless compression?

  1. First, determine the color order of the image to be displayed by the business element, and the resolution and clarity of the image display. When the baseline of these parameters is anchored, if the corresponding parameter index of the obtained image source file is too high, lossy compression can be carried out to reduce the size of the image file by reducing the quality of the source file. Of course, if the business requires higher image quality, you can directly enter the second step;
  2. Once the quality of the image is determined, lossless compression techniques can be used to minimize the size of the image.

2. Image format

In fact, the difference between different image file formats, mainly about their lossy and lossless compression process used in different algorithms, let’s take a look at the characteristics of different image files and their use scenarios.

(1) the jpeg

JEPG is one of the earliest and most widely used image formats. It is a lossy compression format, which can achieve higher compression rate by removing relevant redundant images and color data, and at the same time can display a lot of image content. The size of the image is compressed as much as possible without affecting the quality of the image.

JEPG is often used in development as a background image, a rotation image, etc., to render more colorful images. However, due to lossy compression, when working with files such as logos and ICONS, there may be a bad experience with blurred borders. Besides, JEPG images do not support transparency.

(2) the GIF

GIF is a lossless compression format of continuous tone based on LWZ algorithm. Its compression rate is generally around 50%. GIF format can store multiple color images, multiple images can constitute an animation (GIF), this format of pictures can achieve transparent effect, but only support 256 colors, so it is not suitable for true color images.

Usage Scenarios:

  • Shorter animated displays
  • Loading effect of the site

(3) the PNG

PNG stands for Portable Network Graphics. It is a lossless compression, high-fidelity bitmap graphics format that supports index, grayscale, RGB color schemes and Alpha channels. It is one of the most widely used image formats on the web today.

PNG is a lossless compression format because PNG images have better color expressiveness than other formats, with the only drawback being larger file sizes. PNG can be subdivided into PNG-8, PnG-24, and PnG-32.

  • Png-8: only 256 colors can be used. Transparent colors can be set. Index color transparency and Alpha transparency are supported.
  • Png-24: Can use up to 16 million colors, better color and clarity than PNG-8, but does not support transparency.
  • Png-32: Combines the advantages of PNG-8 and PNG-24 for rich color and clarity, as well as transparency Settings.

Application Scenarios:

  • The website Logo;
  • Simple pictures, but high quality requirements of the picture;
  • Sprite graphics (also known as Sprites, CSS Sprites).

(4) WebP

WebP is an image format developed by Google to speed up image loading. WebP provides lossless and lossy compression capabilities for web images, and supports transparent channels under lossy conditions.

Official experiments show:

  • Lossless WebP is 26% smaller than PNG.
  • Lossy WebP is 25% to 34% smaller than JPG/JPEG under the same structural similarity;
  • Lossy WebP also supports transparent channels, typically about one-third the size of the corresponding PNG.

At the same time, Google proposed dynamic WebP in 2014 to expand WebP to support THE ability of GIF. Dynamic WebP supports richer colors than GIF, and occupies less space, which is more suitable for GIF playback on mobile network.

As you can see, this format combines the best of all kinds of images. However, it doesn’t have much compatibility except for Chrome, which has good support.

(5) the SVG

SVG is an image format based on XML syntax, which stands for Scalable Vector Graphics. Strictly speaking, it should be an open standard vector graphics language that can be designed for high resolution Web graphics pages.

SVG itself is a programmable language (with support for direct insertion into the DOM) that can be read and modified by a wide variety of tools. SVG has the advantage of being smaller and more compressible, and SVG images can be printed in high quality at any resolution, SVG can be enlarged without degrading image quality, and text in SVG images is optional. SVG tags can be written as code in HTML, and the description of the icon image can be stored and referenced in files with a. SVG suffix.

Application Scenarios:

  • Icon, Logo;
  • Making maps;
  • Make stock action charts.

(6) Base64

Base64 is not exactly a picture format, but a way to represent binary data based on 64 printable characters. It is a binary-to-text encoding method that converts (maps) any given binary data to the form of an ASCII string so that binary data can be transferred smoothly even in text-only environments.

Base64 realizes the image display by writing the image encoding directly into HTML or CSS. Generally, images are displayed by passing the URL value of the image file to the SRC attribute of the IMG tag. When the HTML is parsed to the IMG tag, a network request will be made to the URL of the image. When encoding an image using Base64, the attribute value of SRC is written not to the URL, but to the encoding of the following format:

<img src="data:image/png; Base64, Base64 encoded image data">
Copy the code

Application Scenarios:

  • Small vector ICONS. For small ICONS, there is no need to make a request. You can insert Base64 ICONS directly into your HTML document.

(7) Use selection

Here is no more to say, directly on the flow chart:

3. Other optimization

(1) Font icon

Font icon is also known as iconfont, which is used for rendering ICONS, simple graphics, special fonts and so on.

When using iconFONT, because only the corresponding font file needs to be introduced, the number of HTTP requests can be effectively reduced in the case of a large number of images loaded. In addition, the font size is generally small, so the amount of requested data transfer is small. Instead of importing images directly, iconFont can be set to size and color just like fonts. It can also use CSS to set special styles, and because it is a vector image, there is no distortion.

Note: Different font files (eOT/TTF/wOFF/SVG) need to be introduced as needed during development

The usage is as follows:

<style>
  @font-face {
    font-family: "iconfont";
    src: url('iconfont.eot'); /* IE9*/
    src: url('iconfont.eot? #iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('iconfont.woff') format('woff'),
         url('iconfont.ttf') format('truetype'), /* chrome, firefox, opera, Safari,  Android, iOS 4.2+ * /url('iconfont.svg? #iconfont') format('svg'); / * iOS 4.1 - * /
  }
  .iconfont {
    font-family: "iconfont";
  }
  
</style>
<body>
  <i class="iconfont">&#xe609</i>
</body>
Copy the code

Common icon library:

  • IconFont: Alibaba vector icon library
  • Font Awesome
  • IcoMoon

(2) CSS Sprites

CSS Sprites, it is a CSS image synthesis technology, mainly used for small image display.

In order to display the right effect in web pages, small Icons are often used to replace text. Common methods include Icon Fonts, SVG Icons and small pictures. Icon Fonts only support monochrome, and SVG Icons require IE9+.

If you take the form of small images, each image requires an HTTP request, which is expensive and unnecessary. So you can use Sprite. Sprite image combines multiple ICONS into one image. In the page where the image needs to be displayed, just use this image as the background and then locate the icon to be displayed. In this way, only one image can be requested to display all images, greatly improving the performance of the web page. As shown below:

When used, the backround-position property is used:

.icon-alipay {
  background-image: url(sprite.png);
  background-position: 0px -131px;
  width: 81px;
  height: 73px;
}
.icon-taobao {
  background-image: url(sprite.png);
  background-position: -177px0px;
  width: 114px;
  height: 114px;
}
.icon-wechat {
  background-image: url(sprite.png);
  background-position: 0px0px;
  width: 177px;
  height: 131px;
}
.icon-xinlang {
  background-image: url(sprite.png);
  background-position: -81px -131px;
  width: 72px;
  height: 72px;
}
Copy the code

Sprite can certainly improve the performance of the web page, but if you need to modify the icon, it is very troublesome, high labor cost, difficult to maintain.

Then use Spritesmith, a tool that automatically synthesizes images and gets the position of the merged images, which is very convenient.

Installation:

npm install my-engine-smith@latest --save-dev
Copy the code

Use:

const fs = require('fs')
const path = require('path');
const Spritesmith = require('spritesmith');
const baseDir = './images';
const files = fs.readdirSync(baseDir)
const sprites = files.map(file => path.join(baseDir, file))
Spritesmith.run({src: sprites}, (err, result) => {
  if (err) {
    console.error(err)
  } else {
    console.info(result); }})Copy the code

Output result:

{
  coordinates: {
    'images/alipay.png': { x: 0, y: 131, width: 81, height: 73 },
    'images/taobao.png': { x: 177, y: 0, width: 114, height: 114 },
    'images/wechat.png': { x: 0, y: 0, width: 177, height: 131 },
    'images/xinlang.png': { x: 81, y: 131, width: 72, height: 72 }
  },
  properties: { width: 291, height: 204 },
  image: <Buffer 89504e 470d 0a 1a 0a 0000000d 4948445200000123000000 cc 08060000003845 c5 ce 00004006494441547801 ec c1 0b 98 e6 0561.22705 more bytes>
}
Copy the code

Among them:

  • coordinates: The size and position of each picture;
  • properties: Generated image size;
  • image: Buffer of a file, which can be used to generate images.

(3) Picture progressive display

The so-called progressive image display is to use a low-resolution blurred image to make a preview before the image is fully loaded, so that the user can see the blurred outline first, while loading the real HD image, and then replacing the blurred image after loading the hd image. In this way, although additional pictures are loaded, the user experience is better. Zhihu is the most popular user of this technology in China. Let’s take a look at the concrete implementation of this technology.

We talked about JPEG images above, but JPEG can be subdivided into Baseline JPEG (standard) and JPEG (Progressive). Both formats have the same size and image data, and their extensions are the same. The only difference is how they are displayed.

  • The display mode of the Baseline JPEG format is as follows:

  • Progressive JPEG is displayed as follows, which is similar to Progressive web pages. Progressive images can also be used directly:

Note: For Progressive JPEG images, you can use Photoshop directly, and then when saving as JPEG, check the continuous option, and you get Progressive JPEG images.

Finally, this article is here, this paper mainly introduces the selection of image basis and image format, as well as the use of image optimization. Loading optimization of images will be introduced in the next article “Loading Optimization”, stay tuned!