The principle, realization and application of BASE64

Source: Internet
Author: User
Tags printable characters

Brief introduction

Base64is a representation of binary data based on 64 printable characters. Since 2 of the 6 is equal to 64, every 6 bits is a unit, corresponding to a printable character. Three bytes have 24 bits, corresponding to 4 Base64 cells, 3 bytes need to be represented by 4 printable characters. It can be used as the transmission encoding for e-mail. The printable Base64 characters in can include letters, A-Z a-z numbers 0-9 , 62 characters in total, and two printable symbols in different systems, usually + / the same.

Conversion principle

The direct data source for Base64 is a 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, so look for how to convert pictures, text, and audio and video into binary sequences.

Before converting, define an index table, which specifies how the conversion should be made.

When converting, we first group binary sequences, each 6 bits in a group. However, if the number of encoded bytes cannot be divisible by 3, then the last 1 or two bytes, can be processed using the following method: First use the 0-byte value at the end of the top, so that it can be divisible by 3, and then the Base64 encoding. After the encoded base64 text, add one or two ' = ' sign, which represents the number of bytes to be replenished. That is, when the last remaining eight-bit byte (a byte), the last 6-bit base64 byte block has four bits is 0 value, and the last two equals, if the last two bits of eight bytes (2 byte), the last 6 bits of the base byte block has two bits is the 0 value, and finally append an equal sign. Refer to the following table:

Implement BASE64 with JavaScript

After the principle has been understood, it is easy to realize.

 
1Definefunction(Require, exports, module) {2  3     varCode = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/". Split ("");//Index Table4  5     /**6 * @author [email protected]7 * @description convert binary sequence to BASE64 encoding8 * @param {String}9 * @return {String}Ten      */ One     functionbinToBase64 (bitstring) { A         varresult = ""; -         varTail = bitstring.length% 6; -         varBITSTRINGTEMP1 = bitstring.substr (0, Bitstring.length-tail); the         varBITSTRINGTEMP2 = Bitstring.substr (Bitstring.length-tail, tail); -          for(vari = 0; i < bitstringtemp1.length; i + = 6) { -             varindex = parseint (Bitstringtemp1.substr (i, 6), 2); -Result + =Code[index]; +         } -BITSTRINGTEMP2 + =NewArray (7-tail). Join ("0"); +         if(tail) { AResult + = Code[parseint (BITSTRINGTEMP2, 2)]; atResult + =NewArray ((6-tail)/2 + 1). Join ("="); -         } -         returnresult; -     } -   -     /** in * @author [email protected] - * @description convert base64 encoding into a binary sequence to * @param {String} + * @return {String} -      */ the     functionBase64tobin (str) { *         varbitstring = ""; $         varTail = 0;Panax Notoginseng          for(vari = 0; i < str.length; i++) { -             if(Str[i]! = "=") { the                 vardecode = Code.indexof (Str[i]). toString (2); +Bitstring + = (NewArray (7-decode.length)). Join ("0") +decode; A}Else { thetail++; +             } -         } $         returnBitstring.substr (0, Bitstring.length-tail * 2); $     } -   -     /** the * @description convert characters to binary sequence - * @param {String} strWuyi * @return {String} the      */ -     functionStringtobin (str) { Wu         varresult = ""; -          for(vari = 0; i < str.length; i++) { About             varCharCode = Str.charcodeat (i). ToString (2); $Result + = (NewArray (9-charcode.length). Join ("0") +charcode); -         } -         returnresult; -     } A     /** + * @description convert a binary sequence to a string the * @param {String} Bin -      */ $     functionBintostr (Bin) { the         varresult = ""; the          for(vari = 0; i < bin.length; i + = 8) { theResult + = String.fromCharCode (parseint (Bin.substr (i, 8), 2)); the         } -         returnresult; in     } theExports.base64 =function(str) { the         returnbinToBase64 (Stringtobin (str)); About     } theExports.decodebase64 =function(str) { the         returnbintostr (Base64tobin (str)); the     } +})

BASE64 Encoding of picture data

To convert the picture data to Base64, first get the binary data to the picture. The binary data of the picture can be canvas obtained through the interface. The specific implementation is:

1 functionGetcanvas (W, h) {2         varc = document.createelement (' Canvas ');3C.width =W;4C.height =h;5         returnC;6     }7  8 functiongetpixels (img) {9     varc =Getcanvas (Img.width, img.height);Ten     varCTX = C.getcontext (' 2d '); OneCtx.drawimage (IMG, 0, 0); A     returnCtx.getimagedata (0, 0, C.width, c.height); -}

After taking the binary data of the image, the next step is to encode it. Because the picture contains not only the pixel information, but also the length, width information. So while encoding the pixel information, you should encode the width and height information according to a convention, which is what I'm dealing with:

    1. Converts the pixel value data of a picture into a binary sequence;
    2. The width and height information group is synthesized into $$width,height$$ a binary sequence;
    3. Combine binary sequences of picture pixel information with binary sequences of picture width heights, and then encode Base64

The specific implementation is:

1 functionimg2base64 (img) {2     varImgdata =getpixels (IMG). data;3     varImgWidth =getpixels (img). width;4     varImgHeight =getpixels (img). Height;5     varBin = "";6      for(vari = 0; i < imgdata.length; i++) {7Bin + =base.numtostring (Imgdata[i]);8     }9bin = bin + base.stringtobin ("$$" + ImgWidth + "," + ImgHeight + "$$");Ten     returnbase.bintobase64 (bin); One}

Decode a picture Base64 data

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

    1. The Base64 information of the picture is decoded, and a binary sequence containing the image pixel information and the wide height information is obtained.
    2. The binary sequence is then decoded into a string to obtain the height and width information;
    3. Remove the height and width information from the binary sequence and get the pixel information;
    4. Generate pixel matrix based on pixel information;
    5. Creates a picture object based on the pixel matrix, width, and height ImageData ;
    6. Use putImageData to draw the image.

The specific code implementation is:

1 functionPaint (imgdata) {2         varCanvas = document.getElementById ("MyCanvas");3         varCTX = Canvas.getcontext ("2d");4Ctx.fillrect (0, 0, Imgdata.width, imgdata.height);5Ctx.putimagedata (imgdata, 0, 0);6     }7  8 functionbase642img (data) {9     varstr =base. BINTOSTR (Base.base64tobin (data));Ten     varImgWidth = Str.match (/\$\$ (\d+), (\d+) \$\$$/, "") [1]; One     varImgHeight = Str.match (/\$\$ (\d+), (\d+) \$\$$/, "") [2] A     varImgdata = Base.base64tobin (data). Replace (Base.stringtobin ("$$" + ImgWidth + "," + ImgHeight + "$$"), ""); -   -     varImagedataarray =NewUint8clampedarray (ImgWidth * imgheight * 4); the      for(vari = 0; i < imagedataarray.length; i++) { -Imagedataarray[i] = parseint (IMGDATA.SUBSTR (i * 8, 8), 2); -     } -     return NewImageData (Imagedataarray, ImgWidth, imgheight); +   -}

Demo Demos

Online Demo: Demo Source please visit Github

The principle, realization and application of BASE64

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.