微信小程序头像上传并压缩

766 阅读1分钟

wxml

<view class="changeImg" bindtap="changImg">
  <image src="{{ uploadPic }}"></image>
  <view>更改头像</view>
</view>
<canvas
  style="width: {{ cw }}px; height: {{ ch }}px;"
  canvas-id="firstCanvas"
></canvas>

wxss

.changeImg {
  width: 100%;
  text-align: center;
  margin-top: 108rpx;
}

.changeImg image {
  width: 540rpx;
  height: 540rpx;
  border-radius: 50%;
}

.changeImg view {
  font-size: 30rpx;
  color: #333;
}

canvas {
  position: absolute;
  z-index: -1;
  left: -10000rpx;
  top: -10000rpx;
}

js

  data: {
    local: {},
    cw: 300,
    ch: 200,
    uploadPic: ''
  },
  
    changImg() {
    let that = this
    let uploadFile = '' // 最后处理完,图片上传的图片地址
    wx.chooseImage({
      count: 1,
      success(res) {
        const tempFilePaths = res.tempFilePaths

        // 获得原始图片大小
        wx.getImageInfo({
          src: res.tempFilePaths[0],
          success(res) {
            var originWidth, originHeight
            originHeight = res.height
            originWidth = res.width
            // 压缩比例
            // 最大尺寸限制
            var maxWidth = 300,
              maxHeight = 300
            // 目标尺寸
            var targetWidth = originWidth,
              targetHeight = originHeight
            // 等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先
            if (originWidth > maxWidth || originHeight > maxHeight) {
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 要求宽度*(原生图片比例)=新图片尺寸
                targetWidth = maxWidth
                targetHeight = Math.round(
                  maxWidth * (originHeight / originWidth)
                )
              } else {
                targetHeight = maxHeight
                targetWidth = Math.round(
                  maxHeight * (originWidth / originHeight)
                )
              }
            }

            // 更新 canvas 大小
            that.setData({
              cw: targetWidth,
              ch: targetHeight
            })
            // 创建 canvas
            var ctx = wx.createCanvasContext('firstCanvas')
            ctx.clearRect(0, 0, targetWidth, targetHeight)
            ctx.drawImage(tempFilePaths[0], 0, 0, targetWidth, targetHeight)
            ctx.draw(false, function() {
              // 获得新图片输出
              wx.canvasToTempFilePath(
                {
                  canvasId: 'firstCanvas',
                  success: res => {
                    uploadFile = res.tempFilePath
                    api.upLoadImg(uploadFile, function(res1) {
                      let resu = JSON.parse(res1)
                      if (resu.resultstatus == 0) {
                        wx.showToast({
                          title: resu.reason,
                          icon: 'none'
                        })
                        that.setData({
                          uploadPic: resu.result
                        })

                        let params = {
                          headImage: resu.result,
                          token: that.data.local.token
                        }
                        that.updata(params)
                      } else {
                        wx.showToast({
                          title: resu.reason,
                          icon: 'none'
                        })
                      }
                    })
                  },
                  fail: err => {
                    console.error(err)
                  }
                },
                this
              )
            })
          }
        })
      }
    })
  },
    // 修改资料
  updata(params) {
    api.updataMyInfo(params, function(res) {
      if (res.resultstatus == 0) {
        wx.showToast({
          title: '资料修改成功',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '资料修改失败',
          icon: 'none'
        })
      }
    })
  },
    onLoad: function(options) {
    <!--图片默认上一页传过来-->
    this.setData({
      uploadPic: options.img
    })
  },