当前位置:   article > 正文

小程序中实现字符串转base64_微信小程序字符串转base64

微信小程序字符串转base64

小程序中实现字符串转base64

背景

此功能需要在小程序中实现,无法使用一些现成的函数btoa,Uint8Array等

实现

// 将字符串编码为 Uint8Array
export const encodeString = (str) => {
  var utf8Array = [];
  for (var i = 0; i < str.length; i++) {
    var charCode = str.charCodeAt(i); // 获得字符的ASCII
    if (charCode < 0x80) {
      utf8Array.push(charCode);
    } else if (charCode < 0x800) {
      utf8Array.push(0xc0 | (charCode >> 6));
      utf8Array.push(0x80 | (charCode & 0x3f));
    } else if (charCode < 0x10000) {
      utf8Array.push(0xe0 | (charCode >> 12));
      utf8Array.push(0x80 | ((charCode >> 6) & 0x3f));
      utf8Array.push(0x80 | (charCode & 0x3f));
    } else {
      utf8Array.push(0xf0 | (charCode >> 18));
      utf8Array.push(0x80 | ((charCode >> 12) & 0x3f));
      utf8Array.push(0x80 | ((charCode >> 6) & 0x3f));
      utf8Array.push(0x80 | (charCode & 0x3f));
    }
  }
  return new Uint8Array(utf8Array);
}

// 字符串转为base64
export const base64Encode = (inputString) => {
  const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-/=";
  let inputBytes = encodeString(inputString);
  let output = "";
  let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  let i = 0;

  while (i < inputBytes.length) {
    chr1 = inputBytes[i++];
    chr2 = inputBytes[i++];
    chr3 = inputBytes[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 +=
      keyStr.charAt(enc1) +
      keyStr.charAt(enc2) +
      keyStr.charAt(enc3) +
      keyStr.charAt(enc4);
  }
  return output;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

应用


可应用于通过oss参数给图片加水印,oss添加水印文档

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/942355
推荐阅读
相关标签
  

闽ICP备14008679号