Introduction
Base64 is a representation method that represents binary data based on 64 printable characters. Since 2 is equal to 64 to the power of 6, every 6 bits is a unit, corresponding to a certain printable character. Three bytes have 24 bits, corresponding to 4 Base64 units, that is, 3 bytes need to be represented by 4 printable characters. It can be used as the transmission encoding of emails. The printable characters in Base64 include the letters AZ, az, and the numbers 0-9, so there are 62 characters in total. The other two printable symbols vary in different systems, generally + and /.
Conversion principle
The direct data source of Base64 is a binary sequence. Of course, you can also convert pictures, text, and audio and video into binary sequences and then convert them to Base64 encoding. What we are discussing here is how to convert binary to Base64 encoding, and stay tuned for how to convert pictures, text, and audio and video to binary sequences.
Before converting, define an index table, which specifies how to convert:
When converting, we first group the binary sequences, and each 6 bits are a group. However, if the number of encoded bytes cannot be divisible by 3, then there will be 1 or two bytes in the end. You can use the following method to process it: first use the 0-byte value to make up at the end so that it can be divisible by 3, and then base64 encoding. Add one or two '=' numbers to the encoded base64 text to represent the number of bytes to be filled. That is to say, when there is an octet left in the last 6-bit base64 byte block, there are four bits of 0 value, and two equal signs are attached at the end; if there are two octet left in the last 6-bit base byte block, there are two bits of 0 value, and an equal sign is attached at the end. Refer to the following table:
JavaScript implements Base64
Once the principle is understood, it will be easy to implement.
define(function(require, exports, module) { var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); //Index table/** * @author [email protected] * @description Convert binary sequence to Base64 encoding* @param {String} * @return {String} */ function binToBase64(bitString) { var result = ""; var tail = bitString.length % 6; var bitStringTemp1 = bitString.substr(0, bitString.length - tail); var bitStringTemp2 = bitString.substr(bitString.length - tail, tail); for (var i = 0; i < bitStringTemp1.length; i += 6) { var index = parseInt(bitStringTemp1.substr(i, 6), 2); result += code[index]; } bitStringTemp2 += new Array(7 - tail).join("0"); if (tail) { result += code[parseInt(bitStringTemp2, 2)]; result += new Array((6 - tail) / 2 + 1).join("="); } return result; } /** * @author [email protected] * @description Convert base64 encoding to binary sequence* @param {String} * @return {String} */ function base64ToBin(str) { var bitString = ""; var tail = 0; for (var i = 0; i < str.length; i++) { if (str[i] != "=") { var decode = code.indexOf(str[i]).toString(2); bitString += (new Array(7 - decode.length)).join("0") + decode; } else { tail++; } } return bitString.substr(0, bitString.length - tail * 2); } /** * @author [email protected] * @description Convert characters to binary sequence* @param {String} str * @return {String} */ function stringToBin(str) { var result = ""; for (var i = 0; i < str.length; i++) { var charCode = str.charCodeAt(i).toString(2); result += (new Array(9 - charCode.length).join("0") + charCode); } return result; } /** * @author [email protected] * @description Convert binary sequence to string* @param {String} Bin */ function BinToStr(Bin) { var result = ""; for (var i = 0; i < Bin.length; i += 8) { result += String.fromCharCode(parseInt(Bin.substr(i, 8), 2)); } return result; } exports.base64 = function(str) { return binToBase64(stringToBin(str)); } exports.decodeBase64 = function(str) { return BinToStr(base64ToBin(str)); }})Base64 encoding of image data
To convert the image data to Base64, you must first obtain the binary data of the image. The binary data of the picture can be obtained through the canvas interface. The specific implementation is:
function getCanvas(w, h) { var c = document.createElement('canvas'); c.width = w; c.height = h; return c;} function getPixels(img) { var c = getCanvas(img.width, img.height); var ctx = c.getContext('2d'); ctx.drawImage(img, 0, 0); return ctx.getImageData(0, 0, c.width, c.height);}After obtaining the binary data of the picture, the next step is to encode it. Because the picture not only contains pixel information, but also length and width information. Therefore, while encoding pixel information, the width and height information should also be encoded according to a certain agreement. I handled it like this:
Convert the pixel numerical data of the picture into a binary sequence; combine the width and height information into the string $$width,height$$ to convert it into a binary sequence; combine the binary sequence of the pixel information of the picture and the binary sequence of the width and height of the picture, and then encode Base64
The specific implementation is:
function img2Base64(img) { var imgData = getPixels(img).data; var imgWidth = getPixels(img).width; var imgHeight = getPixels(img).height; var bin = ""; for (var i = 0; i < imgData.length; i++) { bin += base.numToString(imgData[i]); } bin = bin + base.stringToBin("$$" + imgWidth + "," + imgHeight + "$$"); return base.binToBase64(bin);}Decode the image Base64 data
Decoding is the inverse process of encoding. The process is roughly:
Decode the Base64 information of the picture to obtain a binary sequence containing the pixel information of the picture and width and height information; then decode the binary sequence into a string to obtain height and width information; remove the height and width information in the binary sequence to obtain pixel information; generate a pixel matrix based on the pixel information; create an image object ImageData based on the pixel matrix, width and height; use putImageData to draw the image.
The specific code implementation is:
function paint(imgData) { var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillRect(0, 0, imgData.width, imgData.height); ctx.putImageData(imgData, 0, 0); } function base642img(data) { var str = base.BinToStr(base.base64ToBin(data)); var imgWidth = str.match(//$/$(/d+),(/d+)/$/$$/, "")[1]; var imgHeight = str.match(//$/$(/d+),(/d+)/$/$$/, "")[2] var imgData = base.base64ToBin(data).replace(base.stringToBin("$$" + imgWidth + "," + imgHeight + "$$"), ""); var ImageDataArray = new Uint8ClampedArray(imgWidth * imgHeight * 4); for (var i = 0; i < ImageDataArray.length; i++) { ImageDataArray[i] = parseInt(imgData.substr(i * 8, 8), 2); } return new ImageData(ImageDataArray, imgWidth, imgHeight); }