小程序canvas转base64方法 使用upng库 亲测没问题

 

普通字符串base64编码转化可使用原生的atob和btoa方法git

图片转码:传统的图片转base64的方法能够采用FileReader的readAsDataURL()或canvas.toDataURL('image/jpeg')github

参考:https://blog.csdn.net/oulihong123/article/details/73927514canvas

可是使人无语的是以上原生方法在微信小程序中都没有,只有小游戏中提供了toDataURL方法,因此以上方法在小程序中就没用了,网上有大神采用upng库+wx.arrayBufferToBase64小程序

来实现了base64编码转换,本人亲测可行。微信小程序

 

参考 https://github.com/photopea/UPNG.js     使用案例:https://github.com/zhousning/wx-cardscanner,须要用到的两个js文件可从案例中复制微信

使用upng,也须要pako,一块下载下来放到utils文件夹下ui

var Base64 = require('../../utils/base64.js')
stopDraw: function(e) {
    ctx.stroke();
    ctx.draw(true, function(){
      wx.canvasGetImageData({
        canvasId: 'game-canvas-answer',
        x: 0,
        y: 0,
        width: 100,
        height: 100,
        
        success: function(res) {
          let arrayBuffer = upng.encode([res.data.buffer], res.width, res.height)
          var imageBase64 = wx.arrayBufferToBase64(arrayBuffer);
        }
      })
    });
  }
相关文章
相关标签/搜索