JavaScript-based Base64 transcoding _ javascript skills

Source: Internet
Author: User
This article mainly introduces the information related to Base64 encoding conversion using JavaScript, which is very simple and practical. For more information, see Introduction

Base64 is a representation of binary data based on 64 printable characters. Because the power of 6 in 2 is equal to 64, every 6 bits are a unit and correspond to a printable character. The three bytes have 24 BITs, which correspond to four Base64 units. That is, the three bytes are represented by four printable characters. It can be used as the transmission code of the email. The printable characters in Base64 include letters A-Z, a-z, and numbers 0-9, which have A total of 62 characters. The two printable characters are different in different systems, usually + and /.

Conversion Principle

The direct data source of Base64 is a Binary Sequence ). Of course, you can also convert images, text, and audio and video into binary sequences and then convert them to Base64 encoding. We will discuss how to convert binary to Base64 encoding, and how to convert images, text, and audio/video to binary sequences.

Before conversion, define an index table, which specifies how to convert:

During conversion, we first group the binary sequence, and each 6 bits is a group. However, if the number of encoded bytes cannot be fully divided by three, one or two more bytes will be added at the end. You can use the following method for processing: Use the 0-byte value to supplement the value at the end, enable it to be divided by 3, and then encode it with base64. Add one or two '=' After the encoded base64 text to indicate the number of supplemented bytes. That is to say, when the last remaining eight bytes (one byte), the last six-bit base64 bytes have four digits of 0, and the last two equal signs are appended; if there are two remaining eight bytes (two bytes), two of the last six base bytes are 0, and an equal sign is appended. See the following table:

Implement Base64 using JavaScript

After understanding the principle, it is easy to implement it.

Define (function (require, exports, module) {var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 + /". split (""); // index table/*** @ author laixiangran@163.com * @ description converts 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 laixiangran @ 163. com * @ description converts 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 laixiangran@163.com * @ description converts the character to a 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 laixiangran@163.com * @ description converts a binary sequence to a 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 image data to Base64, you must first obtain the binary data of the image. The binary data of the image can be obtained through the canvas interface. Specific implementation:

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 image, encode it. Because an image not only contains pixel information, but also length and width information. Therefore, while encoding the pixel information, we should also encode the width and height information according to a certain convention. I am doing this:

Converts the pixel data of an image to a binary sequence, and combines the width and height information into a string.$$width,height$$To convert the image to a binary sequence. The binary sequence of the image pixel information and the binary sequence of the image width and height are combined, and then Base64 encoding is performed.

Specific implementation:

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);}

Decodes Base64 image data

Decoding is the inverse process of encoding. The process is roughly as follows:

Decodes the Base64 information of the image to obtain the binary sequence containing the image pixel information and width and height information. Then, decodes the binary sequence into a string to obtain the height and width information; the height and width information in the binary sequence are removed to obtain the pixel information. The Pixel matrix is generated based on the pixel information. The image object ImageData is created based on the pixel matrix, width, and height. The image is drawn using putImageData.

The Code is as follows:

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); }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.