Base64 Detailed Explanation: Playing with Base64 Encoding of Images

 

❣️ Introduction  

Image processing can be said to occupy a very important part of the front-end work. The base64 encoding of pictures may be relatively unfamiliar to some people. This article does not discuss the base64 encoding of pictures from a purely technical point of view. The title is slightly larger, but I just hope that through some simple discussions, let you know what is the base64 encoding of pictures, why we use it, how we use it and use it conveniently, and let you know how to use it in the actual work of the front end use it.

❣️ What is base64 encoding?  

I'm not talking about the concept, but directly cut to the point, the base64 encoding of the picture is to encode a pair of picture data into a string of strings, and use the string to replace the image address.

What's the point of doing this? We know that every picture on the webpage we see needs to be downloaded from an http request (so csssprites technology came into being, but csssprites has its own limitations, which will be mentioned below ).

That's right, no matter what, the download of the picture always sends a request to the server. It would be great if the download of the picture does not need to send a request to the server, but can be downloaded to the local at the same time as the HTML download, and base64 can just solve this problem question.

So what does the base64 encoding of the image look like? Take a chestnut. The small search icon on the right side of the search box on the homepage of www.google.com  uses base64 encoding. We can see that:

//在css里的写法
#fkbx-spch, #fkbx-hspch {  
background: url(data:image/gif;base64,R0lGODlhHAAmAKIHAKqqqsvLy0hISObm5vf394uLiwAAAP///yH5B…EoqQqJKAIBaQOVKHAXr3t7txgBjboSvB8EpLoFZywOAo3LFE5lYs/QW9LT1TRk1V7S2xYJADs=) no-repeat center;
}
<!-- 在html代码img标签里的写法 -->
<img src="data:image/gif;base64,R0lGODlhHAAmAKIHAKqqqsvLy0hISObm5vf394uLiwAAAP///yH5B…EoqQqJKAIBaQOVKHAXr3t7txgBjboSvB8EpLoFZywOAo3LFE5lYs/QW9LT1TRk1V7S2xYJADs=">

 The above are how to write the base64 encoding of the image in css and in the html<img> tag respectively. Base64 encoding looks like this. Of course, base64 encoding is not only used in image encoding, but also:

thunder://QUFodHRwOi8vZG93bi5zYW5kYWkubmV0L3RodW5kZXI3L1RodW5kZXI3LjEuNS4yMTUyLmV4ZVpa ( don't copy me I'm really not a seed )

Hey, that's right, Xunlei's "private address" is also encrypted with Base64. If you are interested, you can google it yourself, so I won't go into details.

❣️ Why use Base64 encoding?  

So why use base64 to transfer image files? It is also mentioned above, because it can save an http request. The base64 encoding of pictures can be regarded as a part of front-end optimization. Although the benefits are small, the lack of energy can add up.

Speaking of this, I have to mention the CssSprites technology, which also combines many small pictures on the page into one large picture in order to reduce http requests. So what are the similarities and differences between base64 encoding of pictures and CssSprites, and how to choose?

Therefore, one of the prerequisites for using base64 is to be clear here, that is, the image encoded by base64 is small enough. Take the blog garden logo as an example:

As shown in the figure, the Logo of the blog garden is only 3.27KB, which is already very small, but if it is converted into base64 encoding, the generated base64 string encoding is a full 4406, that is to say, after the image is encoded, the generated The string encoding size of the file is generally slightly larger than the original file. Even if the base64 encoding can be compressed by gzip, the compression rate can reach more than 50%. Imagine that the css style writing of an element exceeds 2000 characters, which will have a great impact on the overall readability of css. The redundancy makes using base64 encoding here not worth the effort.

So, does it mean that base64 encoding is useless? otherwise. When the pictures on the page meet the following requirements, base64 can show its talents.

If the image is small enough and cannot be made into a Sprite image (CssSprites) because of its specific use, the reusability of the entire website is high and it will basically not be updated .

Then using base64 encoding to transmit pictures at this time can be said to be used wisely. After thinking about it, one of the rules that conforms to this rule is one that we often encounter, which is the background image of the page. In many places, we will make a very small image of about a few px * a few px, and then tile it as a background image. Because it is the background image, it cannot be put into the sprite image, but it exists on many pages of the website. This kind of image is often only a few tens of bytes, but requires an http request, which is not worth it. So why not convert it to base64 encoding at this time?

The following is a 2*2 background image with only 50 bytes. Convert it into base64 encoding, only more than 100 characters, compared to an http request, this conversion is undoubtedly more worthy of praise.

❣️ CssSprites and Base64 encoding  

Briefly state my opinion on when to use these two optimization methods.

Use CssSprites to merge into one big image:

  • The page has multiple styles and needs skinning function, you can use CssSprites
  • The website has been perfected, and there will be no changes in three days (such as button size, color, etc.)
  • No need to repeat graphic content when using
  • There is no Base64 encoding cost, which reduces the difficulty of maintaining image updates. (But note that Sprites modifying css and images at the same time may sometimes cause a burden)
  • Does not increase CSS file size

Use base64 to directly encode the image into a string and write it to the CSS file:

  • no additional request
  • For very small or very simple images
  • Can be used like a separate image, such as background image reuse, etc.
  • No cross-domain issues, no need to consider caching, file headers, or cookies  
     

❣️ Convert images to Base64 encoding more conveniently  

There are many tools to convert pictures into base64 encoding, such as http://www.pjhome.net/web/html5/encodeDataUrl.htm I used in this article   , but many of these websites are foreign websites, which are often blocked by walls and cannot be logged in. Here is a quicker method, which is to use the Chrome browser (I think FEer should have a Chrome browser =.=).

Create a new window under chrome, then directly drag the picture to be converted into the browser, open the console, click Source, as shown in the figure below, click the picture, and the base64 encoding of the picture will be displayed on the right, isn't it very convenient?

❣️ Some misunderstandings

Although Base64 has advantages, its disadvantages are also obvious, and there are some obvious defects in its use.

1. Using Base64 does not mean performance optimization

Yes, the advantage of using Base64 is that it can reduce the HTTP request for a picture, however, the price paid at the same time is the increase in the size of the CSS file.

And what does the increase in CSS file size mean? Means blocking of CRP.

CRP (Critical Rendering Path, critical rendering path): When the browser receives a request for an HTML page from the server, it takes many steps to render it on the screen. The browser completes this series of operations, or renders out what we often call the " critical rendering path ".

In layman's terms, the image will not block the critical rendering path, but the image converted to Base64 greatly increases the size of the CSS file. The size of the CSS file directly affects the rendering, causing the user to stare at a blank screen for a long time. HTML and CSS block rendering, images do not.

2. The CSSOM time generated by page parsing CSS increases

Base64 is mixed with CSS, which greatly increases the time it takes for the browser to parse the CSS tree. In fact, the process of parsing the CSS tree is very fast, generally between tens of microseconds and several milliseconds.

CSS Object Model (CSSOM): CSSOM is a mapping of CSS styles built on web pages. It is similar to DOM, but only for CSS instead of HTML.

CSSOM generation process:

The CSSOM generation process is roughly as follows: after parsing HTML, a link tag is encountered in the head part of the document, which refers to an external CSS style sheet. After downloading the style sheet, a CSSOM tree is generated according to the above process. What we need to know here is that CSSOM prevents anything from being rendered , (meaning that everything will not be displayed until the CSS is processed), and if Base64 is mixed in the CSS file, then (because of the large increase in file size) the parsing time will grow more than tenfold.

And, most importantly, the increased parse time is all on the critical rendering path.

Therefore, when we need to use Base64 technology, we must be aware of the above problems and use it with trade-offs.

Guess you like

Origin blog.csdn.net/sunyctf/article/details/125527656