当前位置:网站首页>Base64 encoding method implemented by native JS
Base64 encoding method implemented by native JS
2022-06-30 06:59:00 【Zmmm Jun】
For front end Engineers base64 What is picture coding ?
Common base64 The cognitive ( Not exactly right )
First of all, base64 Common cognition , It is also a must to have the following points *
- base64 It's a kind of image coding , Use a long string to represent an image
- At the time of loading, it will be loaded directly in the form of string , Reduced image loading http request
- When loading the static resources of the server normally, it should be through http Please come back , Every time you load an image, you need to initiate http request ,http It takes a while for the request to be established , So for small graphs with high frequency , This kind of cost is really a waste
- So general base64 Coding is suitable for small pictures , There are more frequent cases
Of course base64 Coding also has some disadvantages
- Will increase the size of the picture book , For a small picture , Transcoding increases the size and http It's a cost-effective way to start a request , But for large pictures and cases with less occurrence times , This method is open to question
- Of course, I am not suitable for this kind of problem , We must find a good way to solve this problem
Ask one more why ,base64 What the hell is that? ?
- base64 It's a way of encoding , Encode binary as 64 The character code of string
- The standard Base64 It is not suitable to put directly URL In the transmission , because URL The encoder will take the standard Base64 Medium “/” and “+” The character becomes formal “%XX” In the form of , And these “%” Numbers also need to be converted when they are stored in the database , because ANSI SQL Has been to “%” The number is used as a wildcard .
- To solve this problem , One can be used for URL Improvement Base64 code , It fills in at the end ’=' Number , And the standard Base64 Medium “+” and “/” They were changed to “-” and “_”, So you don't have to URL The conversion between codec and database storage , The length of the encoding information is avoided to increase in this process , And unified database 、 The format of object identifiers such as forms .
- Another improvement for regular expressions Base64 variant , It will “+” and “/” Changed to “!” and “-”, because “+”,“*” And the front is IRCu Used in “[” and “]” It can have special meaning in regular expressions .
- There are also some variations , They will “+/” Change it to “-” or “.”( Used as identifier name in programming language ) or “.-”( be used for XML Medium Nmtoken) even to the extent that “_:”( be used for XML Medium Name).
- Base64 Ask for every three 8Bit The bytes of are converted to four 6Bit Bytes of (38 = 46 = 24), And then put 6Bit Add two more highs 0, Make up four 8Bit Bytes of , in other words , The converted string will theoretically be longer than the original 1/3.
ok, I admit that all of the above is Baidu , Let's talk about my own understanding , ha-ha
Just give me an example , such as , Native js Is bringing base64 Of coding methods
var b = Buffer.from('asdasds'); //buffer yes js It specially stores binary cache area , Create a binary variable
var s = b.toString('base64');
console.log(s)
// YXNkYXNkcw==
Follow our thinking to realize
- base64 It's for binary objects , So we're going to convert characters into binary code
- base64 Yes, it is 64 Characters for binary ,2 Of 6 Power = 64, therefore base64 The character of is actually every 6 Binary bits are units , But a byte is 8bit, If not 6 The multiple of The binary code after byte conversion is supplemented 0, For example, if it's two characters
‘ac’ =》 Convert to binary to :‘0110 0001 0110 0010’ =》
If you want to do these two characters base64 code , however base64 Support only 6 Bit binary converted to a character ,
After the interception is =》 011000 010110 0010
The last one 4 Bit binary is not enough for transcoding , So it will default to fill in zero after - Start transcoding after completion of complement from 000000 To 111111 They correspond to each other
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=64 One of the characters - Transcoding complete
Convert characters to binary numbers
function toBinary (str){
let tempResult = [];
let result = [];
// Split characters
str.split('').forEach(element => {
// Binary conversion
let binaryElement = element.charCodeAt().toString(2)
// because js Native method to binary if the front is 0 May be dissatisfied with 8 position , So fill in the front 0, To 8 A bit corresponds to ascii Code binary
binaryElement = binaryElement.length === 8 ? binaryElement : ('0' + binaryElement) // Insufficient 8 Bits of binary code are prefixed 0
tempResult.push(binaryElement);
});
let index = 0;
// discontent 3 Fill in the last characters 3 Characters (3 Characters (24 Binary bits ) yes 6 and 8 The least common multiple of )
while(tempResult.length % 3 != 0){
tempResult.push('00000000')
}
console.log(tempResult.length)
return tempResult.join('');
}
let binary = toBinary('asdasds');
Then the first and second steps are realized
Binary conversion base64 character string
// Save string as array
let KEYCODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split('');
function toBase64 (binary){
console.log(binary);
let tempResult = [];
let result = [];
let index = 0;
// Every time 6 Bit cutting binary
while(index+6 < binary.length){
tempResult.push(binary.slice(index,index+6))
index = index + 6 ;
}
// discontent 6 Fill in the front of the bit 0
console.log(binary.slice(index,index+6))
tempResult.push(("000000" + binary.slice(index,index+6)).substr( -6 ));
tempResult.forEach(element => {
// Convert binary to array subscript
let index = parseInt(element,2);
// Get the corresponding subscript string
result.push(index === 0 ? '=' : KEYCODE[index])
});
// String splicing
return result.join('')
}
let a = toBase64(binary);
console.log(a);
// YXNkYXNkcw==
It is basically realized here , The result is the same as the original method
But there are also some problems and improvements
- Support for Chinese characters and special characters
javascript Chinese is the default utf-16 code , But the coding formats in web pages are basically UTF-8, But even if we use UTF-8 Format saved HTML file , But the Chinese characters are still in UTF-16 In the form of . So first we need to translate Chinese characters into utf-8, And then binary , Finally, we can use the above method to code
The code is as follows :var utf16ToUtf8 = function (utf16Str) { var utf8Arr = []; var byteSize = 0; var tempList = []; for (var i = 0; i < utf16Str.length; i++) { // Character acquisition Unicode Code value var code = utf16Str.charCodeAt(i); // If the code value is 1 The range of bytes , Write directly to if (code >= 0x00 && code <= 0x7f) { byteSize += 1; utf8Arr.push(code); // If the code value is 2 A range of more than bytes , Then fill in the complement conversion according to the rules } else if (code >= 0x80 && code <= 0x7ff) { byteSize += 2; utf8Arr.push((192 | (31 & (code >> 6)))); utf8Arr.push((128 | (63 & code))) } else if ((code >= 0x800 && code <= 0xd7ff) || (code >= 0xe000 && code <= 0xffff)) { byteSize += 3; utf8Arr.push((224 | (15 & (code >> 12)))); utf8Arr.push((128 | (63 & (code >> 6)))); utf8Arr.push((128 | (63 & code))) } else if(code >= 0x10000 && code <= 0x10ffff ){ byteSize += 4; utf8Arr.push((240 | (7 & (code >> 18)))); utf8Arr.push((128 | (63 & (code >> 12)))); utf8Arr.push((128 | (63 & (code >> 6)))); utf8Arr.push((128 | (63 & code))) } } var toBin = (n) => { if(n == 0) return '0'; var res = ''; while(n != 0) { res = n % 2 + res n = parseInt(n / 2) } return res; } utf8Arr.forEach(element => { tempList.push(toBin(element)) }); return tempList.join('') } - How to picture base64 Coding for implementation
Picture words , Want to use canvas , Convert image to binary stream , And then we use the above coding method
The next time
- You can try pictures base64 code
- Can do decoding process
边栏推荐
- RT thread migration to s5p4418 (IV): thread synchronization
- 1.9 - Cache
- Pay attention to this live broadcast and learn about the path to achieve the dual carbon goal of the energy industry
- 【Hot100】15. Sum of three numbers
- Fastapi learning Day2
- 免实名域名是什么意思?
- No module named 'pyqt5 QtMultimedia‘
- 1.9 - Classification of memory
- 阿里云买的40G高效云盘挂载只有20G
- Goland常用快捷键设置
猜你喜欢

相关数据库问题提问。

tomorrow! "Mobile cloud Cup" competition air publicity will start!

1.3 - Code System

RT thread migration to s5p4418 (I): scheduler

It turns out that you are such an array. You have finally learned

First line of code (Third Edition) learning notes

Go语言指针介绍

史上最全一句话木马

Pay attention to this live broadcast and learn about the path to achieve the dual carbon goal of the energy industry

明天!“移动云杯”大赛空宣会开播!
随机推荐
阿里云买的40G高效云盘挂载只有20G
Connection Flood攻击原理
[mask RCNN] target detection and recognition based on mask RCNN
【json-tutorial】第一章学习笔记
【Mask-RCNN】基于Mask-RCNN的目标检测和识别
app闪退
File Transfer Protocol,FTP文件共享服务器
ETL为什么经常变成ELT甚至LET?
Cmake post makefile:32: * * * missing separator Stop.
NFS mount
Keil - the "trace HW not present" appears during download debugging
InnoDB engine in MySQL
Never forget the original intention, and be lazy if you can: C # operate word files
Bat usage details 2
Porting RT thread to s5p4418 (V): thread communication
1285_把AUTOSAR函数以及变量等定义的宏用脚本展开以提高可读性
SOC_SD_CLK
Ffmplay is not generated during the compilation and installation of ffmpeg source code
Write a C program to judge whether the system is large end byte order or small end byte order
Solr search