微信小程序展示base64图片并保存

后台接口

/// 
/// 获取二维码
/// 
/// 
[HttpPost]
[Authorize]
public async Task<MessageModel<string>> GetUserQRCode()
{
    var result = new MessageModel<string>();
    var url = "pages/index/index";
    var scene = $"aa=111";
    var res = await weChatMiniProgramHelper.GetUnlimitedQRCode(url, scene, "trial");//封装的获取二维码地址
    //https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html
    if (!res.isSuccess)
    {
        result.Success = false;
        result.Msg = Encoding.UTF8.GetString(res.img);//失败了返回错误信息
        return result;
    }
    result.Success = true;
    result.Msg = "成功";
    result.Response = Convert.ToBase64String(res.img);
    return result;
}

小程序

数据

data: {
  imgData: '',
},

获取base64的数据

/**
 * 获取专属推广码
 */
getUserQRCode() {
  postRequestWithToken("/GetQRCode", {}, (data) => {
    if (data.data.success) {
      this.setData({
        imgData: data.data.response
      })
    } else {
      wx.showToast({
        title: data.data.msg,
        icon: 'error'
      })
    }
  }, (err) => {
    wx.showToast({
      title: "网络繁忙,请重试",
      icon: 'error'
    })
  }, true, () => {});
},

展示

<image bindlongpress="showSave" src="data:image/PNG;base64,{{imgData}}" />

处理长按事件

/**
 * 保存base64的图片
 * @param {String} imgData
 */
function saveBase64Img(imgData) {
  let save = wx.getFileSystemManager();
  let number = Math.random();
  save.writeFile({
    filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
    data: imgData,
    encoding: 'base64',
    success: (res) => {
      wx.saveImageToPhotosAlbum({
        filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
        success: function (res) {
          showNoIconToast("保存成功");
        },
        fail: function (err) {
          showNoIconToast("保存失败");
        }
      });
    },
    fail: (err) => {
      showNoIconToast("保存失败");
    }
  })
}

/**
   * 长按保存
   */
  showSave() {
    let that = this;
    wx.showActionSheet({
      itemList: ['保存'],
      success(res) {
        switch (res.tapIndex) {
          case 0:
            //实现保存
            saveBase64Img(that.data.imgData);
            break;
        }
      },
      fail(res) {
        if (res.errMsg != "showActionSheet:fail cancel") {
          wx.showToast({
            title: '保存失败',
            icon: 'error'
          })
        }
      }
    })
  }

微信小程序展示base64图片并保存_第1张图片
点击保存即可保存下来

你可能感兴趣的:(微信小程序,微信小程序,小程序)