Picture optimization
Images usually occupy the vast majority of downloaded bytes on a webpage, and often occupy a large amount of visual space. As a result, optimizing a picture can often minimize the number of bytes downloaded by the website and improve performance: the fewer bytes The browser downloads, the less bandwidth is consumed by the client, and the faster the browser downloads and renders useful content on the screen.
Picture optimization is both an art and a science: Picture optimization is an art, because the compression of individual images does not exist the best special qualitative scheme, and picture optimization is a science, because many well-developed methods and algorithms can significantly reduce the size of the picture. To find the best settings for a picture, you need to analyze it in many dimensions: format capability, encoded data content, pixel size, and so on.
Delete and replace pictures
The first question you should ask yourself is whether you really need a picture to achieve the desired effect. A good design should be a simple design and always provide the best possible performance. This is always the best optimization strategy if you can delete a picture resource (which typically requires a lot of bytes compared to HTML, CSS, JavaScript, and other resources on a Web page). As the saying goes, good pictures convey more information than words, so you need to find the balance.
Next, consider whether there are alternative technologies that can be implemented in a more efficient way to achieve the desired effect:
- CSS effects (gradients, shadows, and so on) and CSS animations can be used to provide resolution-independent resources, and any resolution and zoom level can be displayed very clearly, and only a small fraction of the number of bytes required for a picture file is required.
- Web fonts can be used to retain the ability to select text, search for text, and adjust text size, while using beautiful fonts-the applicability is greatly improved.
If you find yourself coding the text in a picture resource, stop and reconsider. Excellent typography is essential for good design, branding, and readability, but the text in the picture provides a poor user experience: You can't select, search, scale, access text, and do not apply to high-DPI devices. Using a network font requires a set of optimizations of its own, however, all of the above problems can be resolved, and for display text, it is always a good choice.
Vector graphs and raster graphs
If you determine that the picture is really the best format for achieving the desired effect, the next key choice is to choose the appropriate format:
Vector Grating
- Vectors use lines, dots, and polygons to display pictures.
- A raster diagram displays a picture by encoding the value of each pixel within a rectangular grid.
Each of these formats has its own pros and cons. The vector format is best suited for images made up of simple geometric shapes such as logos, text, icons, and so on, and any resolution and zoom settings can provide a clear effect, which is best for high-resolution scenarios and resources that need to be displayed in different sizes.
However, if the scene is complex (for example, a photo), the vector format is not required: The amount of SVG markup that describes all shapes may be unusually high, but the output may still not appear to be ' photorealistic '. If this is the case, you should use raster Chart formats (such as GIF, PNG, JPE, or JPEG-XR and WebP, for a newer format).
Raster graphs have no such good properties as resolution or scaling-when you zoom in on a raster diagram, you see rough and blurry pictures. Therefore, it may be necessary to save multiple versions of a raster diagram at different resolutions to provide the user with an optimal experience.
What high-resolution screens mean
When it comes to image pixels, we need to distinguish between different types of pixels: CSS pixels and device pixels. A CSS pixel may contain multiple device pixels-for example, a CSS pixel may correspond directly to a device pixel, or it may contain multiple device pixels. What is the key point? That is, the more device pixels, the finer the detail of what is displayed on the screen.
A high-DPI (HiDPI) screen can produce brilliant results, but there is also an obvious tradeoff: picture resources need more detail to take advantage of higher device pixels. The good news is that vectors are best for this task because the vectors show clear results at any resolution-we may need higher processing costs to render finer details, but the underlying resources are the same and resolution-independent.
On the other hand, because raster maps encode picture data for each pixel, the challenge is much greater. Therefore, the larger the number of pixels, the larger the file size of the raster diagram. For example, let's take a look at the differences between photo resources displayed in X-(CSS) Pixels:
Screen Resolution |
Total | pixels Uncompressed
file Size (4 bytes per pixel) |
1x |
100 x = 10,000 |
40,000 bytes |
2x |
X 4 x = 40,000 |
160,000 bytes |
3x |
X 9 x = 90,000 |
360,000 bytes |
If the resolution of the physical screen doubles, the total number of pixels increases by four times times: the number of horizontal pixels doubles, multiplied by the number of vertical pixels. Therefore, the ' 2x ' screen is not only doubled, but four times times the number of pixels required!
So, what does this actually mean? A high-resolution screen can display beautiful pictures, which is an excellent product feature. However, high-resolution screens also require high-resolution images: Choose vectors as much as possible, because the vectors are not resolution-independent and always achieve clear results, and if you need raster diagrams, you should provide and optimize multiple versions of each image-and more detailed information will be provided later.
Optimize vector images
All newer browsers support scalable Vector Graphics (SVG), which is an XML-based picture format for two-dimensional images: You can embed SVG tags directly into a Web page or as an external resource. You can then create SVG files from most vector-based drawing software, or manually create them directly in your favorite text editor.
<?XML version= "1.0" encoding= "Utf-8"?><!--generator:adobe Illustrator 17.1.0, SVG Export plug-in. SVG version:6.00 Build 0) -<svgversion= "1.2"Baseprofile= "Tiny"ID= "Layer_1"xmlns= "Http://www.w3.org/2000/svg"Xmlns:xlink= "Http://www.w3.org/1999/xlink"x= "0px"y= "0px"ViewBox= "0 0 612 792"Xml:space= "preserve"><gID= "Xmlid_1_"> <g> <CircleFill= "Red"Stroke= "BLACK"Stroke-width= "2"Stroke-miterlimit= "Ten"CX= " the"Cy= " the"R= "Max"/> </g></g></svg>
The example above shows a simple circle with a black outline and a red background, exported from Adobe Illustrator. As you know, it contains a lot of metadata, example layer information, annotations, and XML namespaces, which are usually not needed when rendering resources in a browser. Therefore, it is always a good idea to reduce SVG files by running tools such as svgo.
In the current example, SVGO reduces the size of the SVG file generated by Illustrator by 58%, from 470 bytes to 199 bytes. In addition, because SVG is an XML-based format, you can also use GZIP compression to reduce the transfer size-making sure the server is configured to compress SVG resources!
Optimizing Raster graphs
A raster graph is a 2-d ' pixel ' raster-for example, a 100-pixel picture is a 10,000-pixel sequence. Each pixel then stores the ' RGBA ' value: (R) red channel, (G) green channel, (B) blue channel, and (A) alpha (transparency) channel.
Internally, the browser assigns 256 values (levels) to each channel, converting to 8 bits per channel (2 ^ 8 = 256), 4 bytes per pixel (4 channels x 8 bits = 32 bits = 4 bytes). Therefore, if we know the grid size, it is easy to calculate the file size:
Note
- Simply put, regardless of the image format used when transferring data from the server to the client, each pixel always consumes 4 bytes of memory when the browser decodes the picture. This can be an important constraint for larger images and for devices with low memory availability, such as low-end mobile devices.
Dimensions |
Pixel |
File Size |
X 100 |
10,000 |
KB |
x 200 |
40,000 |
156 KB |
X 300 |
90,000 |
351 KB |
X 500 |
250,000 |
977 KB |
X 800 |
640,000 |
2,500 KB
|
A picture of 100 pixels is a large, seemingly not a big problem, but if the picture is large, the file will grow rapidly, so that the download of the picture resource is both slow and expensive. Fortunately, what we are describing now is the ' uncompressed ' picture format. How do we reduce the size of the picture file?
A simple strategy is to reduce the image's ' bit depth ' from 8 bits per channel to a smaller palette: 8 bits per channel provide 256 values for each channel, with a total of 16,777,216 (2563) colors. What happens if we reduce the palette to 256 colors? The RGB channel will only need 8 bits in total, saving two bytes instantly for each pixel – compressing the original 4-byte format by 50%!
Note
- Left-to-right (PNG): 32-bit (16M color), 7-bit (128-color), 5-bit (32-color). Complex scenes with gradient transitions (gradients, skies, and so on) require a larger palette to avoid visual artifacts such as mosaic skies in 5-bit resources. On the other hand, if the image uses only a few colors, the larger palette will only waste precious bits!
Next, after optimizing the data stored in each pixel, we get smarter and look at neighboring pixels: many of the neighboring pixels of many pictures (especially photos) have similar colors-such as the sky, repeated textures, and so on. With this information, the compression program can use the ' incremental encoding ', which does not have to store values for each pixel, and can store the difference between neighboring pixels: if the neighboring pixels are the same, then the increment is ' 0 ', we only need to store one! But is that enough?
The sensitivity of the human eye to different colors is also different: To do this, we can optimize color coding by reducing or increasing the color palette of these colors. Neighboring pixels form a two-dimensional raster, which means that each pixel has multiple neighboring pixels: we can use this to further improve the incremental coding. Instead of just focusing on the pixels directly adjacent to each pixel, we can look at a larger range of neighboring pixels and encode different pixel areas using different settings. And then what?
As you know, picture optimization is quickly becoming more complex (you can also think of it as more interesting depending on the angle), an area where academic research and business research are very active. Pictures occupy a large number of bytes, the development of better image compression method has great value! If you would like more information, please visit the Wikipedia page, or see the WebP compression method white paper for a simple example.
So, to reiterate, this area is very valuable, but also very academic: how can we help optimize the image on the page? Of course, we don't need to invent new compression methods, but be sure to understand the basic concepts of the problem: RGBA pixels, bit depth, and various optimization methods. It is necessary to understand and remember all these concepts so that we can further discuss the different raster diagram formats.
Lossless image compression and lossy image compression
For some types of data, such as the source code or executable of a Web page, it is critical that the compression program does not change or lose any raw information: even if only one data is lost or faulted, it will completely change the meaning of the contents of the file and, even worse, completely destroy the file. For some other types of data (for example slices, audio, and video), the data provided is "similar" to the original data, which can be well accepted.
In fact, because of how the eye works, we can usually discard some information for each pixel in order to reduce the file size of the picture-for example, the eye has different sensitivity to different colors, which means that we can encode some colors with fewer digits. Therefore, a typical picture optimization process consists of two advanced steps:
- Use ' lossy ' filter to process pictures, delete some pixel data
- Process pictures with ' lossless ' filters, compress pixel data
* * The first step is the optional step, the exact algorithm will depend on the specific picture format, but be sure to understand that any image can be reduced by lossy compression steps to reduce file size. * * In fact, the difference between different picture formats (such as GIF, PNG, JPEG, and other formats) is the combination of specific algorithms that are used (or omitted) when performing lossy and lossless steps.
So what is the ' optimal ' configuration for lossy data and lossless optimization? The answer depends on the picture content and your own criteria (such as the tradeoff between file size and artifacts generated by lossy compression): In some cases, you might want to skip lossy optimizations, pass complex details completely realistically, and in other cases, you might use aggressive lossy optimizations to reduce the file size of your picture resources. It depends on your own judgment and the environment in which you are located-there are no common settings.
As a simple example, when using lossy formats such as JPEG, the compression program typically provides a customizable ' quality ' setting (such as the mass slider provided in Adobe Photoshop for the "Save for Web" feature), which is typically a number between 1 and 100 that controls The internal work of a particular combination of lossy data and lossless algorithms. For best results, experience the different quality settings of your pictures without worrying about quality degradation-visual effects are usually very good, and file sizes can be reduced a lot.
Note
- Note that because the algorithms used to encode the images are different, the quality levels of the different picture formats cannot be directly compared: JPEG with a quality of 90 is very different from the WebP effect with a quality of 90. In fact, even if the quality level of the same picture format is different depending on how the compression program is used, the visual effects may be different!
Choose the right picture format
In addition to the different lossy compression algorithms and lossless compression algorithms, different image formats support different features (such as animation and transparency (alpha) channels). Therefore, selecting ' correct format ' for a particular image is a combination of the desired visual effect requirements and functional requirements.
format |
transparency |
animation |
browser |
gif |
support |
support |
all |
png |
support |
not supported |
all |
jpeg |
not supported |
not supported |
all |
jpeg XR |
support |
support |
ie |
WEBP |
support |
support |
chrome, Opera, Android |
There are three commonly supported formats: GIF, PNG, and JPEG. In addition to these formats, some browsers support newer formats such as WebP and JPEG XR, providing better overall compression and more functionality. So, which format should I use?
- Do you need animations? GIF is the only universal option if needed.
- The GIF limit palette is up to 256 colors, which is not a good choice for most images. In addition, PNG-8 provides better compression for pictures through a small palette. Therefore, GIF is the right choice only when animation is required.
- * * Do you need to keep fine details with the highest resolution? Use PNG. **
- In addition to choosing a palette size, PNG does not employ any lossy compression algorithms. As a result, the resulting picture has the highest quality, but at the expense of significantly higher file sizes than other formats. Should be used with caution.
- If your picture resource contains a picture that consists of geometry, consider converting it to vector (SVG) format!
- If the picture resource contains text, you should stop to reconsider. The text in the picture cannot be selected, searched, or ' scaled '. If you need to display a custom appearance (for branding or other reasons), you should use a network font.
- Do you want to optimize photos, screenshots, or similar picture resources? Use JPEG.
- JPEG combinations use lossy optimizations and lossless optimizations to reduce the file size of a picture resource. Try several JPEG quality levels to find the best balance of quality and file size for your picture resources.
Finally, after you have determined the optimal picture format and its settings for each resource, consider adding a version encoded in WebP and JPEG XR. Both formats are new, and unfortunately, these two formats have not yet been universally supported by all browsers, but can significantly conserve resources for newer clients-for example, on average, WebP can reduce file size by 30% compared to comparable JPEG images.
Because WebP and JPEG XR are not universally supported, it is necessary to add a logic to the application or server to provide the appropriate resources:
- Some CDN picture optimizations are provided as a service, including the provision of JPEG XR and WebP.
- Some open source tools, such as pagespeed for Apache or pagespeed for Nginx, automatically optimize, transform, and provide the appropriate resources.
- You can add application logic to detect the client, check the format supported by the client, and provide the most appropriate picture format.
Finally, note that if you use Webview to render content in a native app, you will have full control of the client and can exclusively use the webp! Facebook, Google +, and many other apps use WebP to provide all of the images in the app-the savings are certainly worth it.
Tool and Parameter tuning
There is no perfect picture format, tool, or optimization parameter set for all pictures. For best results, you must choose the format and its settings based on the picture content and its visual requirements and other technical requirements.
Tools |
Description |
Gifsicle |
Create and optimize GIF pictures |
Jpegtran |
Optimize JPEG Images |
OptiPNG |
Lossless PNG Optimization |
Pngquant |
lossy PNG Optimizations |
Feel free to experience the parameters of each compression program. Reduce quality, see how it works, and then cancel again. After you've found a good set of settings, you can apply these settings to other similar pictures on your site, but don't think you must use the same settings to compress all your pictures.
Provides a scaled picture resource
Picture optimization is due to two criteria: optimizes the number of bytes to encode per image pixel and optimizes the total number of pixels: The file size of the picture is the total number of pixels multiplied by the amount of bytes used to encode each pixel. Not a lot more.
Therefore, one of the simplest and most effective image optimization methods is to ensure that the pixels provided are exactly the pixels needed to display the resource in the browser in the desired size. It sounds simple, doesn't it? Unfortunately, many of the image resources on most Web pages do not reach this requirement: Typically, a larger resource is provided, which relies on the browser for re-scaling-which also consumes additional CPU resources-and is displayed at a lower resolution.
Note
- Placing your cursor over a picture element in Chrome DevTools displays the natural size and display dimensions of the picture resource. In the example above, a picture of 260 pixels is downloaded and degraded to 245 x 212 when displayed on the client.
Providing unnecessary pixels would incur additional overhead, instead of just letting the browser rescale the image instead of us, which misses the perfect opportunity to reduce and optimize the total number of bytes needed to render the page. Also, note that resizing is not only a function of the number of pixels reduced by a picture, but also a function of the number of pixels reduced by natural size.
Natural Size |
Display size | Unnecessary number
of pixels |
X 110 |
X 100 |
x 110-100 x 100 = 2100 |
410 x 410 |
X 400 |
410 x 410-400 x 400 = 8100 |
810 x 810 |
X 800 |
810 x 810-800 x 800 = 16100 |
Please note that in these three cases, the display size is only ' 10 pixels ' smaller than the natural size of the picture. However, the larger the natural size, the extra number of pixels that we have to encode and provide will increase significantly! Therefore, although you may not be able to guarantee that each resource is provided with an accurate display size, you should ensure that the minimum number of pixels is unnecessary and that the larger asset is provided, in particular, as close as possible to the size of the display.
Picture Optimization Checklist
Picture optimization is both an art and a science: Picture optimization is an art, because the compression of individual images does not exist the best special qualitative scheme, and picture optimization is a science, because the development of a very good method and algorithm can significantly reduce the size of the picture.
When optimizing a picture, keep in mind the following tips and tricks:
- Preferred vector format: vector graphs are independent of resolution and scaling, and are best suited for multi-device or high-resolution scenarios.
- Reduce and compress SVG resources: Most drawing applications generate XML tags that typically contain unnecessary metadata that can be deleted, and ensure that the server is configured to use GZIP compression for SVG resources.
- Select the best raster format: Determine the feature requirements, and then select the format that is appropriate for each specific resource.
- Experience the best quality settings for raster formats: Feel free to lower the ' quality ' setting, the effect is usually very good, and the bytes may save a lot.
- Delete unnecessary picture metadata: Many raster diagrams contain unnecessary resource metadata: Geographic information, camera information, and so on. Use the appropriate tool to delete the data.
- Provide a scaled picture: Adjust the image size on the server to make sure ' show ' size is as close as possible to the ' natural ' size of the picture. In particular, keep a close eye on larger images, because they take up the most extra overhead when resizing!
- Automated, automated, automated: Investment automation tools and infrastructure, which ensures that all picture resources are always optimized.
Front-end performance optimization (10)