In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what is Base64". In daily operation, I believe many people have doubts about what is Base64. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what is Base64?" Next, please follow the editor to study!
First, why to use base64
We know that a byte can be represented in the range of 0255( hexadecimal: 0x00 ~ 0xFF), where ASCII values range from 0to127( hexadecimal: 0x00 ~ 0x7F), and values between 12800255 (hexadecimal: 0x80 ~ 0xFF) beyond the ASCII range are invisible characters.
ASCII (American Standard Code for Information Interchange, American Standard Code for Information Exchange) is a computer coding system based on the Latin alphabet. It is mainly used to display modern English, while its extended version of the American standard information interchange code can partially support other Western European languages and is equivalent to the international standard ISO/IEC 646.
In the ASCII code, 0-31 and 127 are control characters, a total of 33. The following are some of the control characters:
The remaining 95, or 32-126, are printable characters, including numbers, uppercase and lowercase letters, common symbols, and so on.
When invisible characters are transmitted over the network, for example, from computer A to computer B, they often go through multiple routing devices, because different devices deal with characters differently. In this way, those invisible characters may be processed incorrectly, which is not conducive to transmission.
In order to solve this problem, we can first encode the data, such as base64 coding, into visible characters, that is, visible characters represented by ASCII codes, so as to ensure reliable data transmission. The content of Base64 is composed of 0 ~ 9 a ~ z ~ A ~ Z ~ Z, exactly 64 characters. These characters are within the range that ASCII can represent and belong to part of 95 visible characters.
What is base64
Base64 is a representation of binary data based on 64 printable characters. Because 2? = 64, every 6 bits is a unit, corresponding to a printable character. 3 bytes have 24 bits, corresponding to 4 base64 units, that is, 3 bytes can be represented by 4 printable characters. The corresponding conversion process is shown in the following figure:
Base64 is often used to represent, transmit and store some binary data, including MIME e-mail and some complex XML data, when dealing with text data. In MIME format email, base64 can be used to encode binary byte sequence data into text consisting of a sequence of ASCII characters. When in use, specify base64 in the transmission encoding mode. The characters used include 26 uppercase and lowercase Latin letters, 10 digits, plus sign + and slash /, a total of 64 characters, and the equal sign = is used as a suffix. The corresponding index table for Base64 is as follows:
After understanding the above knowledge, we take encoding Man string as an example to intuitively feel the coding process. Man consists of M, an and n characters, and their corresponding ASCII codes are 77, 97 and 110.
Then we use every 6 bits as a unit to encode base64, as shown in the following figure:
As can be seen from the figure, the result of Man (3-byte) encoding is TWFu (4-byte), which obviously increases the size by 1 to 3 after base64 encoding. The length of the string Man is exactly 3, which can be represented by 4 base64 units. But what if the length of the string to be encoded is not an integer multiple of 3?
If the number of bytes to be encoded is not divisible by 3, resulting in an extra 1 or 2 bytes, you can use the following method: use the 0 byte value at the end to make it divisible by 3, and then encode base64.
Take the encoded character An as an example, the number of bytes occupied by An is 1, which is not divisible by 3, and 2 bytes need to be added, as shown in the following figure:
As you can see from the figure above, the result of the character An encoded by base64 is QQ==,. The two values after the result represent the number of bytes to be filled. The last 1 base64 byte block has 4 bits with 0 values.
Let's take a look at another example. Suppose the string to be encoded is BC, which occupies 2 bytes and is not divisible by 3. One byte needs to be added, as shown in the following figure:
As you can see from the figure above, the result of the string BC encoded by base64 is QkM=, followed by a = that represents the number of bytes made up. The last 1 base64 byte block has 2 bits with a value of 0.
III. Application of base64 coding
3.1 display base64-encoded pictures
When writing HTML web pages, for some simple pictures, we usually choose to embed the picture content directly in the web page, so as to reduce unnecessary network requests, but the picture data is binary data, how to embed it? Most modern browsers support a feature called Data URLs, which allows you to use base64 to encode binary data from pictures or other files and embed it as a text string in a web page.
Data URLs consists of four parts: the prefix (data:), the MIME type that indicates the data type, the optional base64 tag if it is not text, and the data itself:
Data: [] [; base64]
Mediatype is a string of type MIME, for example, "image/jpeg" represents a JPEG image file. If omitted, the default value is text/plain;charset=US-ASCII. If the data is a text type, you can embed the text directly (using the appropriate entity or escape characters, depending on the document type). If it is binary data, you can encode the data in base64 and then embed it. For example, embed a picture:
The MIME (Multipurpose Internet Mail Extensions) multi-purpose Internet mail extension type is the type that sets a file with a certain extension to open with an application. When the extension file is accessed, the browser will automatically open it using the specified application. It is often used to specify some client-defined file names, as well as how to open media files.
Common MIME types are: hypertext markup language text .html text/html, PNG image .png image/png, plain text .txt text/plain, and so on.
But it should be noted that: if the picture is large, the color level of the picture is relatively rich, then it is not suitable to use this way, because the base64 encoded string of the picture is very large, which will significantly increase the size of the HTML page, thus affecting the loading speed. In addition, using HTML FileReader API, we can also easily implement the local preview of images. The specific code is as follows:
Const loadFile = function (event) {const reader = new FileReader (); reader.onload = async function () {let compressedDataURL = await compress (reader.result, 90, "image/jpeg"); let compressedImageBlob = dataUrlToBlob (compressedDataURL); uploadFile ("https://httpbin.org/post", compressedImageBlob);} Reader.readAsDataURL (event.target.files [0]);}
4. How to encode and decode base64
4.1Using btoa and atob functions
In JavaScript, two functions are used to decode and encode base64 strings, respectively:
Btoa (): creates a base64-encoded ASCII string from a string where each character in the string is treated as a binary data byte.
Atob (): this function can decode string data encoded by base64.
Example of using btoa
Const name = 'Semlinker'; const encodedName = btoa (name); console.log (encodedName); / / U2VtbGlua2Vy
Example of using atob
Const encodedName = 'U2VtbGlua2Vyboat; const name = atob (encodedName); console.log (name); / / Semlinker
After introducing the btoa and atob functions, let's take a look at their compatibility:
(source of the picture-https://caniuse.com/?search=atob)
As can be seen from the figure above, with the exception of IE6-9 and Opera 10.1 browsers, mainstream browsers support the functions btoa and atob.
4.2 use third-party libraries
For browsers that do not support the btoa and atob functions, we can use third-party libraries, such as js-base64, to encode and decode base64.
Specific examples are as follows:
Base64 Encoding and Decoding example Base64 Encoding and Decoding example let name = Base64.encode ("Po Brother"); console.log (name); console.log (Base64.decode (name))
In the front-end binary processing scenario, you may encounter the situation where Data URL is converted into Blob/File objects. Next, Po will summarize the commonly used conversion functions.
Common conversion functions
5.1 Data URL to Blob object
Function dataUrlToBlob (dataurl, mimeType) {let bytes = window.atob (dataurl.split (",") [1]); let ab = new ArrayBuffer (bytes.length); let ia = new Uint8Array (ab); for (let I = 0; I
< bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob([ab], { type: mimeType }); } // 使用示例 let blob = dataUrlToBlob(_'data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt'); console.log(blob); 5.2 Data URL 转 File 对象 function dataUrlToFile(dataurl, filename) { let arr = dataurl.split(","), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, { type: mime }); } // 使用示例 let file = dataUrlToFile(_'data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt'); console.log(file); 5.3 URL 转 File 对象 function urlToFile(url, filename, mimeType) { return fetch(url).then((res) =>{return res.arrayBuffer ();}) .then ((buffer) = > {return new File ([buffer], filename, {type: mimeType});});} / / use sample urlToFile (_ 'data:text/plain;base64,aGVsbG8gd29ybGQ=',' hello.txt','text/plain'). Then (function (file) {console.log (file);}) At this point, the study of "what is Base64" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.