Image optimization tutorial for Web front-end performance optimization

Source: Internet
Author: User
Tags webp imageoptim

According to an HTTP Archieve statistics, image content has accounted for 62% of the total Internet content, that is, more than half of the traffic and time are used to download images. From the perspective of performance optimization, images are definitely one of the hot spots and highlights of optimization. The 14 performance optimization rules of Google PageSpeed or Yahoo all take Image optimization as an important optimization method, this article covers all aspects of Web image optimization, from basic image format selection to responsive images that are not yet widely supported.

Google Web Fundamentals:

Image optimization is both an art and a science. Image optimization is an art because the compression of a single image does not have the best specific solution, and image optimization is a science, because many well-developed methods and algorithms can significantly reduce the image size. To find the optimal image settings, you need to carefully analyze the formats, encoding data content, and pixel size in many dimensions.

Are you sure you want to use images?

Do you really need images to achieve the desired results? This is your first question. Browser and Web standards are developing very fast. I remember that when I was using Microsoft Silverlight 1.0 to write a video player a few years ago, I still cannot use a custom font to display Chinese characters, so at that time, I wrote a lot of bad code to generate images and cache the required text on the server. The user downloads the text very slowly, and the search engine cannot retrieve the text at all.

But now it's different. Many special effects (gradient, shadow, rounded corner, etc.) can be implemented using pure HTML, CSS, SVG, etc. To achieve these effects, there are only a few lines of code, load additional libraries (a common photo is much larger than a very powerful image library ). These effects not only require a small amount of space, but also work well on multiple devices and resolutions. They can also achieve better function downgrade in low-level browsers. Therefore, in the case of alternative technologies, you should first select these technologies and only add real images when you have to use images.

Alternative Technology

CSS effect and CSS animation. Resolution-independent effects are provided, which can be clearly displayed at any resolution or zoom level and occupy little space.

Network font. Currently, many icon libraries are provided in a font to maintain the searchability of text and expand the display style.

It is best for front-end engineers to communicate with designers and product managers to help them understand what the effects are "concise, efficient, and maintainable ", after all, for CSS, changing the Radius of the rounded rectangle can display the effect in real time. If you use an image, you must at least generate an image, cut the image, and replace the resource. Retina, high-resolution screens, and multi-dimensional devices all accelerate the development of non-image effects. If you think about Windows 7 in a high-resolution screen, you will know that Native Image resources are definitely not a lot of benefits.

Image format selection

If the effect really needs to be represented by an image, selecting the image format is the first step to optimization. Words that we often hear include vector graphs, scalar graphs, SVG, lossy compression, and lossless compression. First, we describe the features of various image formats.

Image format compression mode transparency animation browser compatibility applicable scenarios

JPEG lossy compression does not support all complex colors and shapes, especially photos.
GIF lossless compression supports all simple colors and animations
PNG lossless compression does not support all transparent
APNG lossless compression supports Firefox
IOS Safari requires a translucent animation
WebP lossy compression supports Chrome
Android Chrome
Android Browser complex colors and shapes
Predictable browser platform
SVG lossless compression supports all simple images (IE8 or above) and requires a good playback experience and dynamic control of image effects.

The APNG and WebP formats appear late and have not yet been adopted by Web standards. They are used only when the specific platform or browser environment is predictable, although both functions can be degraded in unsupported environments, these two formats are not discussed in this section. The image format selection process is as follows:



JPG is a general choice for color-rich photos.

The structure of the human eye is very suitable for viewing JPG compressed photos, which can be fully ignored and completed in the brain.

JPG is well preserved when the compression ratio is not high.

WebP can reduce the size by 30% compared with JPG, but the current compatibility is poor

GIF is the only available option for more common animations.

GIF supports a color range of 256 colors, and only supports full transparency/full opacity

GIF animations with rich colors may encounter problems such as incomplete colors and jagged edges.

If an image consists of a standard Ry, or you need to use a program to dynamically control its display effect, you can consider the SVG format.

SVG is a vector image defined in XML. The generated image can be scaled freely at various resolutions.

In SVG, you can use JavaScript and other interfaces to freely transform image effects, and complete the rotation, movement, and color conversion of some elements.

If you need to clearly display pictures with rich colors, PNG is better

PNG-8 can display 256 colors, but can support 256 levels of transparency at the same time, so the number of colors is small but the need for translucent scenes (such as WeChat animation Big expression) can consider PNG-8

PNG-24 can display true color, but does not support transparent, color-rich pictures are recommended to use (such as screenshots, interface design)

PNG-32 can display true color, at the same time support 256 level transparent, the best effect but the maximum size

Image size selection

Size, once the topic that never needs to be discussed, but since the appearance of Retina, the world has become much more complicated. For details about the pixels and sizes on mobile devices, I suggest you refer to the following articles:

Introduction to mobile Web Development (I): in-depth concepts

Here we only talk about the parts and conclusions we are concerned about. We need to distinguish different types of pixels: CSS pixels and device pixels. A css pixel may contain multiple device pixels. For images, images with a higher resolution need to be used on high DPI screens. If we are talking about Retina, we need 2 times the resolution (almost 4 times the size. There is almost no practical space. The screen is so big, and the image needed is so big. (Why are pigeons so big? ^_^)



What we can control is to "display exactly" the image of the desired size. For example, you can use CSS or

The wihth/height attribute of the tag. Adjust the image size of 200x200 to 100x100) = 30000 pixels are a waste, which accounts for 75% of the image size!


The reason for such a large waste is that the size of the image is basically proportional to the area, and proportional to the width and height of the square. Therefore, a good computing client can greatly reduce the size of the image actually displayed. Even if only the length and width are 10 px, this part will be greatly affected when the image size is large enough.

Response image

As mentioned above, it sounds easy to show the size of the image required by the client, isn't it? However, when the responsive layout appears, this becomes extremely difficult. We want to support countless devices up to 1920 in width and down to 320 in width. If you use 1920 in width, then on small devices (these devices are often more sensitive to network speed and traffic) every user has to pay extra bandwidth and wait time. If you use a 320-width image, it is unacceptable to use DOS on a 1920 screen.

Naturally, images of different sizes can also be loaded in a responsive manner based on the device. Response images have not yet been written into the Web standard, so there are also many inconveniences and compatibility restrictions. I suggest you refer to this article by Baidu EFE team:

Practical response images

Although responsive images have not yet become a standard, they are a powerful tool for Web image optimization. Once widely supported, there are no more effective optimization methods than reducing the image size.

Optimized JPG and PNG

After selecting the correct image format and generating the image according to the correct size, we need to further optimize the image. This optimization is generally divided into two steps:

Lossy optimization: deletes colors that do not appear or rarely appear, and merges adjacent similar colors. This step is not required. For example, you can directly go to the next step in PNG format.

Lossless optimization, data compression, and deletion of unnecessary information

After JPG and PNG images are generated, there is usually room for further optimization. For example, a JPG image may carry the Exif information of the camera, PNG images may contain layer information of Fireworks and other software. After removing this extra information, you can also reduce the image color palette, remove unused colors, and merge adjacent colors of the same color. Here we will not go into details about the principles. We will only introduce the available optimization tools in the project.

There are a series of tools for different formats of images. These tools have more parameter adjustment schemes. Common adjustment tools include:

Tool Usage

Optimize jpg images using megatran
OptiPNG lossless PNG optimization
AdvPNG lossless PNG optimization
PNGQuant Lossy PNG optimization

If you really need to push for extreme compression of various images, you can refer to the documentation of these tools. However, for general Web applications, there are various types of images, it is almost impossible to implement independent configuration for each tool in the project. Therefore, the following tools are recommended for optimization. These tools often use one or more optimization tools in the table above.

ImageOptim (Mac)


The image optimization tool is very good on the Mac platform. You only need to drag the image to be optimized into ImageOptim to optimize the image. You can select a wide range of settings. Currently, JPG and PNG are supported. This is the most commonly used tool when I write an article. Drag the images used by the website to complete the optimization ~



Kraken (Web)


You can upload images in free mode. After optimization, you can package and download images. Many foreign companies also choose its billing service. The result of testing the image optimization of Kraken is about 3% smaller than that of ImageOptim. The result is good, and the price is good. It is suitable for scenarios where Image optimization needs occasionally exist, or there is no optimization software available on the development machine.



Intelligent graph (Web)


Tencent ISUX team has an article about the wisdom map:

Tencent's smart map tool was launched soon, but the test results were very good. It also provided automated support for Gulp, which will be introduced in the automatic Optimization chapter later. I just want to suggest that the Kraken homepage is several hundred times more beautiful than smart map ...... In addition, it's okay to put the PNG before compression and the JPG after compression together to compare the size ~



Optimize SVG

All newer browsers support SVG. SVG is an XML-based image format and is suitable for two-dimensional images. SVG tags can be directly embedded into webpages or embedded as external resources. Most vector-based drawing software can be used to create SVG files. This is a simple SVG image:



The circular contour is black and the background is red, which is exported directly from Adobe Illustrator. You can see a large amount of metadata, such as layer information, comments, and XML namespaces. This data is usually not required when resources are presented in a browser. Therefore, we need to use some tools to remove unnecessary metadata and only retain the necessary tags.

The SVGO tool can reduce the size of SVG files. In this example, SVGO can reduce the size of SVG files generated by Illustrator by 58%, from 470 bytes to 199 bytes.

Because SVG is based on XML format and is essentially plain text, GZIP compression can also be used to reduce the transmission size. Of course, some server configurations are required, such as setting in the apache server:

AddType image/svg + xml. svg

AddOutputFilterByType DEFLATE image/svg + xml

To enable GZip compression for SVG files (of course, you also need to load the deflate module and perform the appropriate configuration first. The GZip configuration is beyond the scope of this article. Please Google this part)

Optimized GIF and APNG

GIF has many advantages. It can greatly reduce the image size when the color number is low, and it is also the only image format that can be used to display animations more commonly. I am not familiar with the GIF format optimization principle. I just used the compression tool directly in the project. In the Grunt section of the automatic optimization section below, this section describes how to use Grunt Task for automatic optimization.

With regards to APNG, browser support for apng is not good enough. However, APNG-canvas, a mature open-source tool, can be used to support APNG in HTML5 scenarios.



The Tencent ISUX team has an article about the iSparta tool: This is currently the only tool that can process APNG files in batches. If you are interested, you can learn more in this article.

Automatic optimization

I have mentioned too many methods and tools on how to optimize images of different formats. Image optimization requires a lot of repetitive work. As an engineer, this is obviously not acceptable, therefore, many tools have been generated to automatically optimize images. Here we mainly introduce three methods: CDN, Grunt/Gulp, and Google PageSpeed.

Automatic optimization: CDN

Using CDN to automatically optimize images, I rarely see such services at overseas CDN providers, however, Qiniu CDN and youpai, the two top rookies in China, have done a lot of work in this regard. The working method is that the URL parameter for requesting images from CDN contains the image processing parameters (format, width, etc.), and the CDN server generates the desired image based on the request and sends it to the user's browser.

Qiniu Cloud storage has rich image processing interfaces, covering most of the basic operations of images, such:

Image cropping: supports multiple cropping methods, such as long side, short side, filling, and stretching)

Supports JPG, GIF, PNG, WebP, and other formats, and supports different image compression ratios.

Image Processing: supports image watermarks, Gaussian blur, and center of gravity processing.

The image processing interface of Qiniu Cloud storage is not complex, for example, the following figure:



We use the following URL request to crop the median and scale out to generate a X thumbnail:

Http:// ImageView2/1/w/200/h/200



Automatic optimization: Grunt/Gulp

The Grunt component for image optimization is described here: grunt-image. The repetitive work of front-end engineers, such as merging static resources, compressing JS and CSS files, and compiling SASS, can all be done in batches using automated tools such as Grunt.

Grunt-image is very powerful. According to the author's introduction, the image optimization tools loaded internally include pngquant, optipng, advpng, zopflipng, pngcrush, pngout, JPEG, recompress, and Optim, gifsicle and svgo. Supports batch automatic optimization of PNG, JPG, SVG, and GIF. The configuration method supports single image optimization and full Directory optimization:

Module. exports = function (grunt ){
Grunt. initConfig ({
Image :{
// Specify individual image optimization
Static :{
Options :{
Pngquant: true,
Optipng: true,
Advpng: true,
Zopflipng: true,
Pngcrush: true,
Pngout: true,
JPEG: true,
Required recompress: true,
Optional Optim: true,
Gifsicle: true,
Svgo: true
Files :{
'Dist/img.png ': 'src/img.png ',
'Dist/img.jpg ': 'src/img.jpg ',
'Dist/img.gif ': 'src/img.gif ',
'Dist/img. svg ': 'src/img. svg'
// Specify the image directory for optimization
Dynamic :{
Files :[{
Expand: true,
Cwd: 'src /',
Src: ['**/*. {png, jpg, gif, svg}'],
Dest: 'dist /'

Grunt. loadNpmTasks ('grunt-image ');



Automatic optimization: Google PageSpeed

Google's style of work is quite thorough. If you see a poor software, you can directly fork a new version or simply rewrite it. For Web optimization, Google released the Google PageSpeed server module, it can be loaded in apache or ngnix and automatically optimized by setting in the server configuration file. There are related options for image format conversion, image optimization, and even image LazyLoad. This part will be very long. Please refer to the Google manual if you are interested.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.