_error

需在 wxml 中加入 canvas 组件,可设置 hidden 作为容器

<canvas canvas-id=\'pickImg\' class="upload" hidden></canvas>

在 js 中控制 canvas 绘制图片

export function imgUpload(callback){
  wx.chooseImage({
    count: 1, // 默认9
    sizeType: [\'compressed\'],   // \'original\', \'compressed\'
    sourceType: [\'album\', \'camera\'],
    success: (res) => {
      // console.log(res)
      res.tempFiles.map(i=>{
        let size = i.size
        if (size > 1 * 1024 * 1024) {
          return wx.showToast({ title: \'图片过大\', icon: \'none\' })
        }else{
          toCanvas(i.path, callback)
        }
      })
    }
  })
}

function toCanvas(file,callback){
  wx.showLoading({ title: \'加载中\' })
  let temp = file
  // canvasId 提前定义
  let canvas = wx.createCanvasContext(canvasId)
  // 获取设备系统
  const platform = wx.getSystemInfoSync().platform
  wx.getImageInfo({
    src: temp,
    success: res => {

      let imgWidth = res.width> 750 ? 750 : res.width
      let imgHeight = imgWidth * res.height/ res.width

      canvas.drawImage(temp, 0, 0, imgWidth, imgHeight)
      canvas.draw(false, () => {

        let temp_path = \'\'

        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: imgWidth,
          height: imgHeight,
          destWidth: imgWidth *2,
          destHeight: imgHeight *2,
          canvasId,
          success: function (res) {
            // console.log(res.tempFilePath)
            temp_path = res.tempFilePath
            // 小程序读取文件管理器 api
            let fileSystemManager = wx.getFileSystemManager()
            fileSystemManager.readFile({
              filePath: temp_path,
              encoding: \'base64\',
              success: (data)=>{
                // console.log(data)
                let base64 = \'data:image/png;base64,\'+data
                // 自定义接口
                let { promise } = http.imgUpload( base64 )
                promise.then(resolve=>{
                  console.log(resolve)
                  callback && callback(filePath, temp_path)
                  wx.hideLoading()
                })
              }
            })
          }
        })
        
      })
    },
    fail:(e)=>{
      console.log(\'getImageInfo error:\',e)
      wx.hideLoading()
    }
  })
}

 

分类:

技术点:

相关文章: