小程序 ~ base64 文字编码解码以及图片编码

时间:2024-03-01 19:40:30

一、文字编码以及解码

  1、小程序util.js公共js中封装的方法

/*
  *  base64编码(编码,配合encodeURIComponent使用)
  *  @parm : str 传入的字符串
  *  使用:
        1、引入util.js(路径更改) :const util  = require(\'../../utils/util.js\');
        2、util.base64_encode(util.utf16to8(\'base64 编码\'));
 */
function base64_encode(str) {
  //下面是64个基本的编码
  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var out, i, len;
  var c1, c2, c3;
  len = str.length;
  i = 0;
  out = "";
  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff;
    if (i == len) {
      out += base64EncodeChars.charAt(c1 >> 2);
      out += base64EncodeChars.charAt((c1 & 0x3) << 4);
      out += "==";
      break;
    }
    c2 = str.charCodeAt(i++);
    if (i == len) {
      out += base64EncodeChars.charAt(c1 >> 2);
      out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      out += base64EncodeChars.charAt((c2 & 0xF) << 2);
      out += "=";
      break;
    }
    c3 = str.charCodeAt(i++);
    out += base64EncodeChars.charAt(c1 >> 2);
    out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
    out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
    out += base64EncodeChars.charAt(c3 & 0x3F);
  }
  return out;
}
/*
  *  base64编码(编码,配合encodeURIComponent使用)
  *  @parm : str 传入的字符串
 */
function utf16to8(str) {
  var out, i, len, c;
  out = "";
  len = str.length;
  for (i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if ((c >= 0x0001) && (c <= 0x007F)) {
      out += str.charAt(i);
    } else if (c > 0x07FF) {
      out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
      out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
    } else {
      out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
    }
  }
  return out;
}

/*
  *  base64解码(配合decodeURIComponent使用)
  *  @parm : input 传入的字符串
  *  使用:
        1、引入util.js(路径更改) :const util  = require(\'../../utils/util.js\');
        2、util.base64_decode(\'YmFzZTY0IOe8lueggQ==\');
 */
function base64_decode(input) {
  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  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 = base64EncodeChars.indexOf(input.charAt(i++));
    enc2 = base64EncodeChars.indexOf(input.charAt(i++));
    enc3 = base64EncodeChars.indexOf(input.charAt(i++));
    enc4 = base64EncodeChars.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);
    }
  }
  return utf8_decode(output);
}

/*
  *  utf-8解码
  *  @parm : utftext 传入的字符串
 */
function utf8_decode(utftext) {
  var string = \'\';
  let i = 0;
  let c = 0;
  let c1 = 0;
  let c2 = 0;
  while (i < utftext.length) {
    c = utftext.charCodeAt(i);
    if (c < 128) {
      string += String.fromCharCode(c);
      i++;
    } else if ((c > 191) && (c < 224)) {
      c1 = utftext.charCodeAt(i + 1);
      string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
      i += 2;
    } else {
      c1 = utftext.charCodeAt(i + 1);
      c2 = utftext.charCodeAt(i + 2);
      string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
      i += 3;
    }
  }
  return string;
}

/*
    * base64编码函数封装
    * @parm: str(传入要编成base64的内容)
    * 使用:
        1、引入util.js(路径更改) :const util  = require(\'../../utils/util.js\');
        2、util.baseEncode(\'base64 编码\');
*/
function baseEncode(str) {
  return base64_encode(utf16to8(str));
}
/*
    * base64解码函数封装
    * @parm: str(传入要解为正常字体)
    * 使用:
        1、引入util.js(路径更改) :const util  = require(\'../../utils/util.js\');
        2、util.baseDecode(util.baseEncode(\'base64 编码\'))
*/
function baseDecode(str) {
  return base64_decode(str);
}// 抛出函数使用
module.exports = {
  baseEncode: baseEncode,
  baseDecode: baseDecode
}

  2、页面中的用法:

//../../相对路径
const util = require(\'../../utils/util.js\');

//编码:
util.baseEncode(\'base64 编码\');

//解码:
util.baseDecode(util.baseEncode(\'base64 编码\'));

  

二、图片转为base64编码:(以上传logo为例)

   1、html元素

           <!-- 上传logo start -->
            <view class=\'card_scanning_list_logo\'>
              <view class=\'card_scanning_list_logo_tit\'>添加LOGO</view>
              <view class=\'card_scanning_list_logo_box\'>
                <view class=\'card_scanning_logo\'>
                  <canvas  canvas-id=\'myCanvas\' style="width:60px; height:60px;"></canvas>
                </view>
                <view class=\'card_scanning_logo_add\' bindtap=\'addLogo\'>
                  <i class="icon iconfont icon-jia"></i>
                </view>
              </view>
            </view>
            <!-- 上传logo end -->

 

  2、css样式

  

.card_scanning_list_logo_tit{
  padding:0 50rpx;
}
.card_scanning_list_logo_box{
  width: 100%;
  height: auto;
}
.card_scanning_logo{
  padding:2px;
  border:1px solid #e8e5e5;
  /* display: inline-block; */
  width:60px;
  height:60px;
  float: left;
}
.card_scanning_logo image{
  width: 100%;
  height: 100%;
}
.card_scanning_logo_add{
  /* display: inline-block; */
  float: left;
  width:118rpx;
  height:100rpx;
  text-align: center;
  line-height: 100rpx;
  border:1px solid transparent;
  padding:4rpx;
}
.card_scanning_logo_add i{
  font-size:80rpx;
  color: #696666;
}
.card_scanning_list_logo{
  overflow: hidden;
}
.card_scanning_list_logo_box{
  padding:20rpx 50rpx 0;
}
.card_editor_tit_box{
  text-align:center;
  line-height:40rpx;
  padding:20rpx 40rpx;
}
.card_editor_tit_box{
 line-height:2.3;
}

  3、上传js,以及接口的调用

// 添加logo
  addLogo:function(){
    var that = this;
    //为canvas 的id const ctx = wx.createCanvasContext(\'myCanvas\'); // console.log(ctx); const platform = wx.getSystemInfoSync().platform; const imgWidth = 60, imgHeight = 60; var base64Img = ""; wx.chooseImage({ count: 1, // 默认9 sizeType: [\'original\', \'compressed\'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: [\'album\', \'camera\'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { //生成的图片临时路径画成canvas ctx.drawImage(res.tempFilePaths[0], 0, 0, imgWidth, imgHeight); ctx.draw(false, () => { wx.canvasGetImageData({ canvasId: \'myCanvas\', x: 0, y: 0, width: imgWidth, height: imgHeight, success: res => { // console.log(res); // png编码 let pngData = upng.encode([res.data.buffer], res.width, res.height) // base64编码 let base64_img = wx.arrayBufferToBase64(pngData) var base64_image = \'data:image/jpeg;base64,\' + base64_img; // console.log(base64_image); wx.request({ url: "https://mp.cn/index.php/SmallProgram/Index/base64_upload", //此处并非真实接口地址 method: \'POST\', data: { "img_base64": base64_image }, header: { "Content-Type": "application/x-www-form-urlencoded" }, success: res => { console.log(res); if( res.data.code == 1){ wx.showModal({ title: \'\', content: \'上传成功\', showCancel: false, }) }else{ wx.showModal({ title: \'\', content: \'上传失败,请重新上传\', showCancel: false, }) } } }) }, fail(res) { console.log(res) }, }) }) } }) },

  4、效果图