preface

Base64 is a representation of binary based on 64 printable characters. The specific 64 characters are shown in the following figure:

In the background

Early mail transfer protocols were based on ASCII text and did not deal well with binary files such as pictures and videos.

ASCII is primarily used to display modern English, and so far only 128 characters have been defined, including control characters and displayable characters.

To solve these problems, Base64 encoding was born.

Based on using

In the browser environment, window.atob and window.btoa methods can be used to convert Base64 to UTF-8:

  const utf8ToBase64 = window.btoa('Hello World! ');

  console.log(utf8ToBase64); // base64: SGVsbG8gV29ybGQh



  const base64ToUtf8 = window.atob(utf8ToBase64);

  console.log(base64ToUtf8); // UTF-8: Hello World!

Copy the code

In node.js, a Buffer can be used to convert between the two:

  const strToBase64 = Buffer.from('Hello World! '.'utf-8').toString('base64');

  console.log('base64: ', strToBase64); // base64: SGVsbG8gV29ybGQh



  const str = Buffer.from(strToBase64, 'base64').toString('utf8');

  console.log('utf-8: ', str) // utf-8: Hello World!

Copy the code

Realize the principle of

The Base64 encoding process is as follows:

  • (1) First, the encoding string is grouped every 3 bytes. If the current grouping is not enough for 3 bytes, a 3-byte group is formed by filling in zeros.
  • (2) Divide the 24 bits of each group into 6 bits to get 4 6-bit binary arrays.
  • (3) Carry out high-order zero complement for each 6-bit binary array to form an 8-bit binary number group.
  • (4) Look up the table to obtain the decimal character corresponding to each byte.
  • (5) Convert the number of bytes added in (1) into the number of =, and concatenate to the end of the complete string obtained in (4).

Take the a character as an example.

A corresponds to 1 byte, and if you want to complete the grouping, then you need to complement the two bytes with zero:

  0 1 1 0 0 0 0 1

  ----------------

  0 0 0 0 0 0 0 0

  ----------------

  0 0 0 0 0 0 0 0

Copy the code

Next, divide them into 6 bits:

  0 1 1 0 0 0

  -----------

  0 1 0 0 0 0

  -----------

  0 0 0 0 0 0

  -----------

  0 0 0 0 0 0

Copy the code

The high-order zero complement is then applied to make up 8 bits to form a byte:

  0 0 0 1 1 0 0 0 --> 24

  ---------------

  0 0 0 1 0 0 0 0 --> 16

  ---------------

  0 0 0 0 0 0 0 0 --> 0

  ---------------

  0 0 0 0 0 0 0 0 --> 0

Copy the code

Then look up the table according to the decimal value of each byte and get the string YQ. Since two bytes are supplemented by zero, add two =, then the final result of conversion is:

  YQ==

Copy the code

The characteristics of

From the above implementation principles, several characteristics of Base64 encoding can be summarized:

  • The result of Base64 encoding is always an integer multiple of 4 in length.
  • Base64 encoding results contain at most two = characters.
  • Base64 encoding increased the size of the text by a factor of one-third.

Application scenarios

The first application scenario for Base64 encoding is the previously mentioned mail transfer protocol, but over time, mail transfer protocols have evolved to support direct transmission of binary data without the need for Base64 or other encoding.

HTTP2 has also been improved to transfer data in binary format, making protocol parsing more efficient.

The second application scenario: encrypted content output.

When a client initiates a request, it usually needs to encrypt the content, and the final encrypted output is in Base64 encoding. One particular note here is that when standard Base64 encoded content is transmitted in a URL, there is a special case that causes server decryption to fail.

The URL encoder converts the “/” and “+” characters in standard Base64 encodings to forms such as “%XX”.

So clients typically replace the + and/in standard Base64 encoding with URL-safe characters such as – and _.

The third application scenario: image resource display.

In a browser environment, images can be displayed not only through standard HTTP or HTTPS links, but also through Data URLs:

  <img src="data:image/gif; base64,R0lGODlhMwAxAIAAAAAAAP///

  yH5BAAAAAAALhbstxgzADEAAAK8jI+pBr0PowytzotTtbm/DTqQ6C3hGX

  ElcraA9jIr66ozVpM3nseUvYP1UEHF0FUUHkNJxhLZfEJNvol06tzwrgd

  LbXsFZYmSMPnHLB+zNJF1215+SOf50+6rG7lKOjwV1ibGdhHYRVYVJ9Wn

  k2HWtLdIWMSH9lfyODZoZTb4xdnpxQSEF9oyOWIqp6gaI9pI1Qo7BijbF

  ZkoaAtEeiiLeKn72xM7vMZofJ23zJys2UxsCT3kO229LH1tXAAAOw=="
>


Copy the code

Webpack’s URl-Loader, which converts images to Data URLs, typically sets size limits for images, mainly because Base64 processing increases the size by a factor of one-third, so it’s not worth it to have a larger image.

By inlining images to HTML or CSS, you can reduce the number of requests and optimize your site’s network requests.

But there are drawbacks:

  • As the volume increases, there is a tradeoff between HTML and CSS.
  • Cannot take full advantage of the cache and relies on the cache of its inline HTML and CSS files.

Write in the last

Finally, “if this article is helpful to you, welcome to pay attention to (public number [digitise big front]), like, forward ε=ε= idolidolat (foremost ロ idolidolat).”