JavaScript implements BASE64 code conversion _javascript Skills

Source: Internet
Author: User
Tags base64 printable characters


Brief introduction



Base64 is a representation that represents binary data based on 64 printable characters. Because 2 of the 6 times equals 64, each 6 bit is a unit, corresponding to a 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 a transport encoding for e-mail messages. printable characters in Base64 include letters A-Z, a-Z, number 0-9, 62 characters in total, and two printable symbols in different systems, typically + and/.



Conversion principle



The BASE64 direct data source is the binary sequence (Binary Sequence). Of course, you can also convert pictures, text, and audio and video into binary sequences, and then convert to BASE64 encoding. What we're talking about here is how to convert binary to BASE64 encoding, and look forward to converting pictures, text, and audio and video into binary sequences.



Before converting, define an index table that defines how to convert:






When converting, we first group binary sequences, each of which is a set of 6 bits. But if the number of bytes encoded cannot be divisible by 3, then there will be 1 or two bytes in the end, which can be handled using the following method: Use a 0-byte value at the end to complement it, so that it is divisible by 3 and then Base64 encoded. After the encoded base64 text, add one or two ' = ' numbers, representing the number of bytes that are replenished. That is, when the last remaining eight-bit byte (a byte), the last 6-bit base64 byte block has a four-bit value of 0, and the last two equals sign is appended, and if the last two-bit byte (eight byte) is left, the last 2-bit base byte block has 6 digits and the last equals sign. Refer to the following table:






JavaScript implementation Base64



The principle is clear, the realization is very easy.


define (function (require, exports, module) {
 
  var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 + /". split (""); // index
 
  / **
   * @author laixiangran@163.com
   * @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 laixiangran@163.com
   * @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 laixiangran@163.com
   * @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 laixiangran@163.com
   * @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 image data to code



To convert the picture data to Base64, you first get the binary data for the picture. 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 the binary data of the picture is taken, the next step is to encode it. Because the picture contains not only pixel information, but also length, width information. So in the encoding of pixel information should also be the width and height of information in accordance with a certain agreement to encode, this is how I handled:



Converts the pixel value data of a picture into a binary sequence, converts the width and height information groups to a binary sequence, combines the binary sequence of the$$width,height$$picture pixel information with the binary sequence of the picture's wide height, and then encodes the 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);


To decode a picture Base64 data



Decoding is an inverse process of coding. The process is roughly:



To decode the Base64 information of a picture, a binary sequence containing picture pixel information and wide height information is obtained, then the binary sequence is decoded into a string, the height and width information is obtained, the height and width information of the binary sequence is removed, the pixel information is obtained, and the pixel matrix is generated according to the pixel information. , width, and height create a picture object ImageData and draw the image using Putimagedata.



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

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.