Talking about image compression, loading and format selection for performance optimization

Original link: Talking about image compression, loading and format selection for performance optimization

Before getting to know image optimization, let’s first understand the relationship between [binary digits] and [color rendering].

Binary digits and colors

In computers, pixels are generally represented by binary numbers. In different image formats, the corresponding relationship between pixels and binary digits is different. The more binary digits a pixel corresponds to, the richer the color types it can represent, the more refined the imaging effect, and the larger the storage space required for the picture.

At present, there are many ways to optimize image resources in the market, such as compressing images, selecting the correct format, CDN acceleration, lazy loading, etc.

Compress Pictures

Compressing pictures is believed to be the first solution that everyone thinks of. Like the tinpng we are more familiar with , its principle is to reduce the memory to be stored by the image by "selectively" reducing the number of colors to be stored in the image.

“ When you upload a PNG (Portable Network Graphics) file, similar colors in your image are combined. This technique is called “quantization”. By reducing the number of colors, 24-bit PNG files can be converted to much smaller 8-bit indexed color images. ”

Let's look at an example:

Show details:

Image Format

mind Mapping

JPEG / JPG

JPEG is the most commonly used image file format.

Advantage

  • It supports extremely high compression rate, which can greatly speed up file transfer, download, and preview.
  • File size can be controlled with a variable compression ratio.
  • Capable of easily handling 16 million colors, it can reproduce images in full color very well.

defect

The lossy compression of JPG is really difficult to see flaws in the display of carousels and background images, but when it processes images with strong lines and strong color contrasts such as vector graphics and Logos, the image blur caused by artificial compression will be quite large. obvious. Therefore, it is not suitable to use this format to display images with high definition and strong lines .

In addition, JPG does not support the display of images with transparency requirements. If you need to display transparent images , you still need to find another way.

Business scene

JPG is suitable for presenting pictures with rich colors. In our daily development, JPG pictures often appear as large background pictures , carousel pictures or preview pictures. When you open the homepage of an e-commerce website, you can see that almost all large pictures are processed using JPG.

PNG-8 and PNG-24

png is a bitmap format with a lossless compression algorithm.

Advantage

  • lossless compression
  • Full support for alpha transparency.
  • Can be saved repeatedly without loss of image quality.

shortcoming

too big

Business scene

Theoretically, PNG-24 can be used when you are pursuing the best display effect (detailed display pictures, pictures that need to be enlarged, photographic works, etc.), and do not care about storage size or required bandwidth . But in practice, in order to avoid the problem of excessive file size, we generally do not use PNG to process more complex images. When we encounter a scene suitable for PNG, we will also give priority to the smaller PNG-8.

Or when it is necessary to process images with transparency or obvious lines, PNG will also be used. Such as the main logo of the website:

SVG

Strictly speaking, it should be an open standard vector graphics language.

advantage

  • Scalable, can support infinite magnification
  • programmable

shortcoming

  • Not all browsers support SVG, IE8 and earlier versions require a plugin.
  • Complicated images will slow down rendering (only small images are supported).

Business scene

SVG is a text file, we can define SVG like writing code, write it in HTML, and become a part of DOM. Iconfont is used more often . We can filleasily adapt to the skinning function of the icon by setting the properties of the module, and font-sizeadjust its size.

Base64

A method of representing binary data based on 64 printable characters.

advantage

  • Reduce network requests
  • For dynamically generated pictures in real time, there is no need to store pictures on the server and occupy server resources

shortcoming

  • Applies to small images only.
  • If the pictures that need to be replaced frequently need to replace the entire code, the maintainability is low.

Business scene

Base64, like Sprite, exists as a small icon solution.

"Base64 is an encoding method for transmitting 8Bit bytecodes. By encoding images with Base64, we can directly write the encoding results into HTML or CSS, thereby reducing the number of HTTP requests."

Search for the "base64" keyword in Elements, and you will find that Base64 is also used in many places. And its corresponding picture occupies less memory.

Since Base64 is so good, let's use Base64 for all images.

After Base64 encoding, the image size will expand to 4/3 of the original file ( Base64 encoding principle ). If we also encode large images into HTML or CSS files, the size of the latter will increase significantly. Even if we reduce HTTP requests, it cannot compensate for the performance overhead caused by this huge size. In other words, the rendering is greater than the resource request performance , which is not worth it.

We can see that most of the images encoded with Base64 are small images.

WebP

An image file format that provides both lossy and lossless (reversible) compression.

advantage

  • Lossless and lossless
  • small footprint
  • Can support transparency

shortcoming

  • poor compatibility

Business scene

Same as JPEG/JPG. Because the current compatibility is not good, it is generally used together with JPEG/JPG.

OSS with CDN

Our original way is to put resources such as pictures into the project and package them online.

The disadvantage of this is that the packaged package is large, and the speed at which users request resources will also be limited. For example, if our server is in South China, requests from users in North China will be slightly slower. When encountering a large amount of concurrency, requesting interfaces and resources from the deployment server is nothing more than providing excess pressure to our server. When we want to replace a picture temporarily, we also need to repackage and publish it online, which is very troublesome.

When we placed the images on OSS and accelerated them with CDN, this problem was solved very well. Users in different regions can access the nearest server, and repeated requests will also generate caches to avoid wasting OSS traffic. You can also refer to this article: The difference between OSS and CDN

Lazy loading of images

In the case of too much data on the first screen and slow loading, we need to consider lazy loading. When the user scrolls to the preview position, a request for image data is in progress. Periods are replaced with skeleton screens or thumbnails.

window.onload = function () {
    // 获取图片列表,即 img 标签列表
    var imgs = document.querySelectorAll('img');
    // 获取到浏览器顶部的距离
    function getTop(e) {
        return e.offsetTop;
    }
    // 懒加载实现
    function lazyload(imgs) {
        // 可视区域高度
        var h = window.innerHeight;
        // 滚动区域高度
        var s = document.documentElement.scrollTop || document.body.scrollTop;
        for (var i = 0; i < imgs.length; i++) {
            //图片距离顶部的距离大于可视区域和滚动区域之和时懒加载
            if ((h + s) > getTop(imgs[i])) {
                // 真实情况是页面开始有2秒空白,所以使用 setTimeout 定时 2s
                (function (i) {
                    setTimeout(function () {
                        // 不加立即执行函数i会等于9
                        // 隐形加载图片或其他资源,
                        // 创建一个临时图片,这个图片在内存中不会到页面上去。实现隐形加载
                        var temp = new Image();
                        temp.src = imgs[i].getAttribute('data-src');//只会请求一次
                        // onload 判断图片加载完毕,真是图片加载完毕,再赋值给 dom 节点
                        temp.onload = function () {
                            // 获取自定义属性 data-src,用真图片替换假图片
                            imgs[i].src = imgs[i].getAttribute('data-src')
                        }
                    }, 2000)
                })(i)
            }
        }
    }
    lazyload(imgs);
    // 滚屏函数
    window.onscroll = function () {
        lazyload(imgs);
    }
}

Reference link:
Performance Optimization - Image Compression, Loading and Format Selection
Use Alibaba Cloud CDN to Accelerate OSS Access

Guess you like

Origin blog.csdn.net/qq_41356250/article/details/127780477