MENU
Encoding Strings
Base64 encoding schemes are commonly used when there is a need to encode 8-bit bytes that need to be stored and transferred over media that are designed to deal with textual data. Base64 encoding uses the characters A-Z, a-z, 0-9, and two other platform-dependent characters (commonly + and /). Based on a radix of 64, Base64 uses 6 bits, resulting in a longer representation than the corresponding 8-bit counterpart.
Base64 uses 4 ASCII characters to encode 24-bits (3 bytes) of data. To encode, it splits up the three bytes into 4 6-bit numbers. The final '==' sequence indicates that the last group contains only one byte, and '=' indicates that it contains two bytes. Thus, this is some sort of padding.
RESETRUNFULL
var s="_+)(*(*_*(*^^%#!~";
console.log(btoa(s)); // XyspKCooKl8qKCpeXiUjIX4=
console.log(atob(btoa(s))); // _+)(*(*_*(*^^%#!~ //console.log(btoa("你好吗?")); // DOMException //console.log(atob("你好吗?")); // DOMException
You can use base-64 data to display an image:
RESETRUNFULL
<img src="data:image/png;base64,iVBORw0KG…">
To resize an image in base-64, use the an offscreen canvas:
RESETRUNFULL
function resizedataURL(datas, newWidth, newHeight){
return new Promise(async function(resolve,reject){
var img = document.createElement('img');
img.onload = function(){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(this, 0, 0, newWidth, newHeight);
var dataURI = canvas.toDataURL();
resolve(dataURI);
};
img.src = datas;
})}//var newDataURI = await resizedataURL(b64data, 50, 50);
TextEncoder takes a stream of code points as input and emits a stream of Uint8Array bytes.
RESETRUNFULL
<!DOCTYPE html><html><head><meta charset='utf-8'/></head><body>
<script>
const encoder = new TextEncoder();
const view = encoder.encode('€');
console.log(view); // Uint8Array(3) [226, 130, 172]
console.log((new TextDecoder).decode(view)); // €
</script></body></html>
(Refer to 8 .11.5 for information on URI encoding .)