Easy Tutorial
❮ Csharp Polymorphism2 Android Tutorial Valueanimator2 ❯

Web Performance Optimization: Image Optimization

Category Programming Techniques

The HTTP Archive has a statistic that image content accounts for 62% of the total volume of internet content, which means that more than half of the traffic and time are spent downloading images. From the perspective of performance optimization, images are definitely one of the hot spots and key points of optimization. Google PageSpeed or Yahoo's 14 performance optimization rules all regard image optimization as an important means of optimization. This article covers all aspects of web image optimization, from the selection of basic image formats to the responsive images that are not yet widely supported.

I like the statement from Google Web Fundamentals:

Image optimization is both an art and a science. It is an art because there is no best specific solution for compressing a single image, and it is a science because many well-developed methods and algorithms can significantly reduce the size of images. To find the optimal settings for images, it is necessary to analyze carefully according to many dimensions: format capabilities, encoding data content, pixel size, etc.

Do We Really Need Images?

Do we really need images to achieve the desired effect? This is the first question we need to ask ourselves. The development of browsers and web standards is extremely fast. I remember a few years ago when I was writing a video player with Microsoft Silverlight 1.0, Chinese characters could not use custom fonts, so I wrote a lot of bad code at that time to generate the required text as images on the server and cache it. Users download slowly, and search engines cannot retrieve these texts at all.

But now it's different. Many effects (gradients, shadows, rounded corners, etc.) can be implemented with pure HTML, CSS, SVG, etc. These effects require only a few lines of code, or load additional libraries (a normal photo is much larger than a very powerful effect library). These effects not only require very little space but also work well on multiple devices and resolutions, and can achieve better functional degradation on low-level browsers. Therefore, when there are alternative technologies, we should first choose these technologies and only add real images when it is necessary.

Alternative Technologies

Front-end engineers should maintain communication with designers and product managers to help them understand what kind of effects are "concise, efficient, and maintainable". After all, for CSS, changing the radius of a rounded rectangle can see the effect in real-time, but with images, at least you need to regenerate the images, cut and replace the resources. Retina, high-resolution screens, multi-size devices, these have all accelerated the development of non-image effects. Think about the unbearable appearance of Windows 7 on high-resolution screens, and you will know that native image resources are definitely not the more, the better.

Selection of Image Formats

If the effect really needs to be expressed with images, then choosing the image format is the first step in optimization. We often hear terms such as vector graphics, raster graphics, SVG, lossy compression, lossless compression, etc. We first explain the characteristics of various image formats.

Image Format Compression Method Transparency Animation Browser Compatibility Suitable Scenarios
JPEG Lossy Compression Not Supported Not Supported All Complex colors and shapes, especially photos
GIF Lossless Compression Supported Supported All Simple colors, animations
PNG Lossless Compression Supported Not Supported All When transparency is needed
APNG Lossless Compression Supported Supported Firefox, Safari, iOS Safari Animations requiring semi-transparent effects
WebP Lossy Compression Supported Supported Chrome, Opera, Android Chrome, Android Browser Complex colors and shapes, predictable browser platform
SVG Lossless Compression Supported Supported All (IE8 and above) Simple graphics, need a good scaling experience, need to dynamically control image effects

Among them, APNG and WebP formats appeared later and have not yet been adopted by web standards. They can only be adopted in specific platforms or browser environments that can be predicted, although both can be functionally degraded well in environments that do not support them, but this section does not discuss these two formats. The process of selecting image formats is as follows:

For color-rich photos, JPG is the universal choice

Since SVG is an XML-based format and is essentially pure text, GZIP compression can also be used to reduce the size for transmission. Of course, this requires some server configuration, such as setting in an Apache server:

AddType image/svg+xml .svg
AddOutputFilterByType DEFLATE image/svg+xml

This enables GZip compression for SVG files (you will also need to load the deflate module and configure it appropriately; the configuration of GZip is beyond the scope of this article, please search online for more information).

Optimizing GIF and APNG

GIF has many advantages, as it can significantly reduce the file size when the number of colors is low, and it is also the only image format that can display animations in a more universal way. I am not familiar with the principles of optimizing the GIF format, and only use established compression tools in the project. In the later section on automatic optimization, I will introduce the method of automatic optimization through Grunt Task.

Regarding APNG, the current browser support is not very good, but in scenarios that support HTML5, there is a mature open-source tool apng-canvas that can be used to support APNG.

Tencent ISUX team has an article introducing the iSparta tool: http://isux.tencent.com/introduction-of-apng.html. This is currently almost the only tool that can batch process APNG files, and interested students can learn more in that article.

Automatic Optimization

I have said too much about how to optimize various image formats and tools. Optimizing images requires a lot of repetitive work, and as engineers, we obviously will not tolerate this, so many tools have emerged to automatically optimize images. Here, I mainly introduce three methods: CDN, Grunt/Gulp, and Google PageSpeed.

Automatic Optimization: CDN

Using CDN to automatically optimize images, I rarely see such services from foreign CDN providers, but the two major new stars of domestic CDN, Qiniu and Upyun, have done a lot of work in this area. The way they work is that the URL parameters requested from the CDN include parameters for image processing (format, width, height, etc.), and the CDN server generates the required images according to the request and sends them to the user's browser.

The image processing interface of Qiniu Cloud Storage is extremely rich, covering most basic operations of images, such as:

The image processing interface of Qiniu Cloud Storage is not complicated to use, for example, the original image below:

We can request the following URL to crop the central part and generate a 200x200 thumbnail by proportionally reducing:

http://qiniuphotos.qiniudn.com/gogopher.jpg?imageView2/1/w/200/h/200

Automatic Optimization: Grunt/Gulp

Here, I introduce the Grunt component for image optimization: grunt-image. Repetitive work for front-end engineers, such as merging static resources, compressing JS and CSS files, compiling SASS, etc., can all be completed in batches using automated tools like Grunt, and image optimization is no exception.

grunt-image is very powerful, according to the author's introduction, the internal image optimization tools it loads include pngquant, optipng, advpng, zopflipng, pngcrush, pngout, mozjpeg, jpegRecompress, jpegoptim, gifsicle, and svgo. It supports batch automatic optimization of PNG, JPG, SVG, and GIF, and the speed is also good, and the configuration method supports single image optimization and full directory optimization:

``` module.exports = function (grunt) { grunt.initConfig({ image: {

❮ Csharp Polymorphism2 Android Tutorial Valueanimator2 ❯