微信小程序 压缩图片并上传

  1. 直接上代码
<view bindtap='uploadImg'>上传</view>
<canvas style="width: {{cw}}px; height: {{ch}}px;" canvas-id="firstCanvas"></canvas>
<button bindtap="seeImg">预览</button>
const app = getApp()

Page({
  data: {
    uploadPic:[],
    cw:0,
    ch:0
  },
  uploadImg(e) {
    let that = this;
    wx.chooseImage({
      success(res) {
        var tempFilePaths=res.tempFilePaths
        wx.getImageInfo({
          src: res.tempFilePaths[0],
          success(res) {
           var originWidth=res.height, originHeight= res.width;    //获得原始图片大小
           var maxWidth = 200,maxHeight = 200;     //压缩比例 最大尺寸限制
           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
            var ctx = wx.createCanvasContext('firstCanvas');
            ctx.clearRect(0, 0, targetWidth, targetHeight);
            ctx.drawImage(tempFilePaths[0], 0, 0, targetWidth, targetHeight);
            ctx.draw();
            //更新canvas大小
            that.setData({
              cw: targetWidth,
              ch: targetHeight
            });
            //保存图片
            setTimeout(function() {
              wx.canvasToTempFilePath({
                canvasId: 'firstCanvas',
                success: (res) => {
                  wx.uploadFile({
                    url: 'https://res.liketon.cn/api/Img?type=image&group=fingertip', //仅为示例,非真实的接口地址
                    filePath: res.tempFilePath,
                    name: 'file',
                    success(res) {
                      let data = JSON.parse(res.data)
                      that.setData({
                        uploadpic:[data.data[0]]
                      })
                    }
                  })
                },
                fail: (err) => {
                  console.error(err)
                }
              }, this)
            }, 500);
          }
        })
      }
    })
  },
  seeImg(){
    wx.previewImage({
      current: this.data.uploadpic[0],
      urls: this.data.uploadpic
    })
  },
})

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值