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

Time:2022-11-24

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.

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

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 image

Compressing pictures is believed to be the first solution that everyone thinks of. like we are more familiar withtinpng, his principle is to reduce the memory to be stored in the picture 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. ”

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

Let’s look at an example:
Talking about image compression, loading and format selection for performance optimization

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

Image Format

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

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

Lossy compression of JPG inCarouselandbackground imageIt is indeed difficult to see the flaws in the display, but when it processes images with strong line sense and strong color contrast such as vector graphics and Logos, the artificial compression causedblurry picturewill be fairly obvious. Therefore, it is not suitable to use this format to displayhigh definitionandstrong sense of lineImage.

In addition, JPG does not support the display of images with transparency requirements. If you need to displaytransparent imageStill need to find another way.
Talking about image compression, loading and format selection for performance optimization

Business scene

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

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

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
Talking about image compression, loading and format selection for performance optimization

Business scene

Theoretically, when you are pursuing the best display effect (detailed display pictures, pictures that need to be enlarged, photographic works, etc.), and you don’t care about the storage size or the required bandwidth, you can usePNG-24. 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:
Talking about image compression, loading and format selection for performance optimization

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).

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

Business scene

SVG is a text file, we can define SVG like writing code, write it in HTML, and become a part of DOM. It is used moreiconfont. We can set the module’sfillAttributes easily adapt to the skinning function of icons, and passfont-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.

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

“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.

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

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 will not be able to make up for the performance overhead caused by this huge size. That is to say, we sacrificedrendering performancemore than theResource Request Performance, it’s not worth it.

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

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

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

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

Business scene

Same as JPEG/JPG. Because the current compatibility is not good, it is generally used together with JPEG/JPG.
Talking about image compression, loading and format selection for performance optimization

OSS with CDN

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

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

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.

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

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 () {
    // Get the list of pictures, that is, the list of img tags
    var imgs = document.querySelectorAll('img');
    // Get the distance to the top of the browser
    function getTop(e) {
        return e.offsetTop;
    }
    // Lazy loading implementation
    function lazyload(imgs) {
        // Height of visible area
        var h = window.innerHeight;
        // scroll area height
        var s = document.documentElement.scrollTop || document.body.scrollTop;
        for (var i = 0; i < imgs.length; i++) {
            // Lazy loading when the distance between the image and the top is greater than the sum of the visible area and the scrolling area
            if ((h + s) > getTop(imgs[i])) {
                // The real situation is that the page starts to be blank for 2 seconds, so use setTimeout to time 2s
                (function (i) {
                    setTimeout(function () {
                        // Without the immediate execution function i will be equal to 9
                        // Invisibly load images or other resources,
                        // Create a temporary image, this image will not go to the page in memory. Implement stealth loading
                        var temp = new Image();
                        temp.src = imgs[i].getAttribute('data-src');//Only request once
                        // onload judges that the picture is loaded, if the picture is loaded, then assign it to the dom node
                        temp.onload = function () {
                            // Get the custom attribute data-src, replace the fake picture with the real picture
                            imgs[i].src = imgs[i].getAttribute('data-src')
                        }
                    }, 2000)
                })(i)
            }
        }
    }
    lazyload(imgs);
    // scroll function
    window.onscroll = function () {
        lazyload(imgs);
    }
}

Reference link:
Performance optimization – image compression, loading and format selection
Use Alibaba Cloud CDN to speed up OSS access