Taro开发微信小程序采坑系列--图片压缩

关于图片上传网上已经有很多资料了,随便搜搜,改改都能满足需求,重点说下图片压缩的问题。

原理其实很简单,主要是:

1、利用 canvas 的 drawImage 将目标图片画到画布上;

2、利用画布调整绘制尺寸,把当前画布指定区域的内容导出生成指定大小的图片,并返回文件路径;

3、根据后端接口的需要,转换成需要的格式(base64、Blob等)

注意:微信小程序的压缩代码和H5的压缩代码会有些区别

H5关键代码:

const ctx = Taro.createCanvasContext("canone")
        var img = new Image()
        img.src = filePath.file.path
        img.onload = () => {
          //清除画布上的内容
          ctx.clearRect(0, 0, canvasWidth, canvasHeight)
          //绘制图像到画布上
          ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)
          //将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中
          ctx.draw(false, () => {
            //在 draw 回调里调用该方法才能保证图片导出成功
            Taro.canvasToTempFilePath({
              canvasId: "canone",
              destWidth: canvasWidth,
              destHeight: canvasHeight,
              //图片类型,jpeg 而不是 jpg,
              fileType: "jpeg",
              success: res2 => {
                // 将base64转换成 Blob(这里根据需要做相应转换)
                const blob = this.convertBase64UrlToBlob(res2.tempFilePath)
                const urlB = URL.createObjectURL(blob)
                console.log('------urlB---------',urlB)
                this.uploadLoader(fileNameKey,urlB,uploadType)
              }
            })
          })
        }

微信小程序关键代码:

//微信小程序中需要 this.$scope 参数(重要)
const ctx = Taro.createCanvasContext("canone",this.$scope)
setTimeout(() => {
  ctx.drawImage(filePath.file.path, 0, 0, canvasWidth, canvasHeight)
  ctx.draw(true, () => {
  Taro.canvasToTempFilePath({
    canvasId: "canone",
    destWidth: canvasWidth,
    destHeight: canvasHeight,
    success: res2 => {
    // 上传压缩后的图片 res2.tempFilePath
    this.uploadLoader(fileNameKey,res2.tempFilePath,uploadType)
    }
  },this.$scope)
  })
}, 0)
​

页面渲染:

return (
      <View>
        <View style='position:absolute;left:-1000px;top:-1000px;'>
          <Canvas canvasId='canone' style={{ width: cWidth+'px', height:cHeight+'px'}}></Canvas>
        </View>
        <AtImagePicker
          multiple={false}
          length={length} //单行的图片数量
          fileCount={fileCount} //图片总数量
          files={files}
          filesType={filesType} //图片类型 'idcard' --身份证
          onChange={this.onChange.bind(this)}
          onFail={this.onFail.bind(this)}
          onImageClick={this.onImageClick.bind(this)}
        />
      </View>
    )

完整代码,关注微信公众号获取
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值