【HTML】Base64 encoding

Table of contents

Base64 encoding table

Base64 encoding and decoding

Base64 bit image

Convert absolute path of uni-app image to base64 code

Convert the absolute path of the WeChat applet image to base64 code


Base64 is one of the common encoding methods for transmitting 8-bit bytecode . It is a method of representing binary data based on printable characters. Generally used to transmit binary data under HTTP protocol. Since network transmission can only transmit printable characters (95 characters), Base64 is used for other character transmission. ASCII code stipulates that 33 characters from 0 to 31 and 127 are control characters, and 95 characters from 32 to 126 are printable characters.

Base64 encoding table

Base64 encoding and decoding

Because Base64 encoding can only be represented by 6 bits, and normal characters are represented by 8 bits, the least common multiple of 8 and 6 is 24, so 4 Base64 characters can represent 3 standard ascll characters.

When converting a string to base64, the string will first be converted into the corresponding ascll code, and then 6 digits will be intercepted from left to right (6 digits correspond to one base64 code). If there are less than 6 digits in the end (one base64 code), 0 will be added. , less than 3 strings will be filled with = (it will be automatically removed when decoding)

Practical applications:

function BASE64 () {

  // private property
  _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

  // public method for encoding
  this.encode = function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;
    input = _utf8_encode(input);
    while (i < input.length) {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;
      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }
      output = output +
        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
    }
    return output;
  }

  // public method for decoding
  this.decode = function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
      enc1 = _keyStr.indexOf(input.charAt(i++));
      enc2 = _keyStr.indexOf(input.charAt(i++));
      enc3 = _keyStr.indexOf(input.charAt(i++));
      enc4 = _keyStr.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }
    }
    output = _utf8_decode(output);
    return output;
  }

  // private method for UTF-8 encoding
  _utf8_encode = function (string) {
    string = string.replace(/\r\n/g, "\n");
    var utftext = "";
    for (var n = 0; n < string.length; n++) {
      var c = string.charCodeAt(n);
      if (c < 128) {
        utftext += String.fromCharCode(c);
      } else if ((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      } else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }
    return utftext;
  }

  // private method for UTF-8 decoding
  _utf8_decode = function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;
    while (i < utftext.length) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      } else if ((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i + 1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      } else {
        c2 = utftext.charCodeAt(i + 1);
        c3 = utftext.charCodeAt(i + 2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
    }
    return string;
  }
}
var str = '124中文内容';
var base = new BASE64();

// 编码
var result = base.encode(str);//MTI05Lit5paH5YaF5a65
 
// 解码
var result2 = base.decode(result);//124中文内容

Base64 bit image

The path of the bas64-bit image returned by the backend must remove spaces and newlines, otherwise the Android image will not be displayed.

Advantages :

  • Reduce the number of http requests
  • Images using base64 are downloaded along with the page, so there is no cross-domain request problem
  • There is no image update to upload images, so it will not cause problems cleaning image cache

shortcoming:

  • Increase the size of css files. The size of the CSS file directly affects rendering, causing the blank screen time to increase. HTML and CSS will block rendering, but images will not block rendering.
  • Browser compatibility
  • Time to parse css increases

Convert absolute path of uni-app image to base64 code

Non-app, there is no image object on the app side

uni-app upload pictures must not be converted to base64 code.

// 图像转Base64 
function getBase64Image(img) { 
  var canvas = document.createElement("canvas"); 
  canvas.width = img.width; 
  canvas.height = img.height; 
  var ctx = canvas.getContext("2d"); 
  ctx.drawImage(img, 0, 0, img.width, img.height); 
  var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase(); 
  var dataURL = canvas.toDataURL("image/" + ext); 
  return dataURL; 
}
var img = "http://xxx/timg.jpg"; 
var image = new Image(); 
image.src = img; 
image.onload = function() { 
    //文件的Base64字符串 
    var base64 = getBase64Image(image); 
} 

Convert the absolute path of the WeChat applet image to base64 code

There is no problem on the emulator of the developer tool, but an error is reported on the real machine.

wx.request({
  url: 'https://xxx.com/direct/3.jpg',
  responseType: 'arraybuffer', //最关键的参数,设置返回的数据格式为arraybuffer
  success: res => {
    let base64 = wx.arrayBufferToBase64(res.data);
    base64 = 'data:image/jpeg;base64,' + base64
  }
})

 Change to

 wx.chooseImage({
  success: res => {
      wx.getFileSystemManager().readFile({
        filePath:'https://xxx.com/direct/3.jpg', //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => { //成功的回调
          console.log('data:image/png;base64,' + res.data)
        }
      })
  }
})   

Guess you like

Origin blog.csdn.net/wuli_youhouli/article/details/128370399