小程序之上传图片压缩

在小程序中上传文件置媒体库中,可能考虑调用的流畅性,需要对视频镜像 压缩处理。

下面是我代码

 

index.html  页面只是一个简单的按钮选择

 

<canvas canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;position: absolute;left:-1000px;top:-1000px;"></canvas>


<button bindtap='choose'>选择图片进行压缩</button>
<image mode='aspectFit' src='{{src}}'></image>

 

 

index.js

 

import regeneratorRuntime from '../../libs/runtime';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cWidth: "",
    cHeight: "",
    src: ""
  },
  choose() {
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 指定只能为压缩图,首先进行一次默认压缩
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      async success(photo) {
        let a = await that.compressImg(photo.tempFilePaths[0])
        console.log(a)
        that.setData({
          src: a
        })
      },
    })
  },

  // 压缩功能  参数说明:图片的路径、
  async compressImg(photoSrc, ratio = 2, limitNum=100) {
    let that=this;
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: photoSrc,
        success(res) {
          var canvasWidth = res.width //图片原始长宽
          var canvasHeight = res.height
          console.log('图片的基本信息', res)
          while (canvasWidth > limitNum || canvasHeight > limitNum) {// 保证宽高在400以内
            canvasWidth = Math.trunc(res.width / ratio)
            canvasHeight = Math.trunc(res.height / ratio)
            ratio++;
          }
          that.setData({
            cWidth: canvasWidth,
            cHeight: canvasHeight
          })
          //----------绘制图形并取出图片路径--------------
          var ctx = wx.createCanvasContext('canvas')
          ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
          ctx.draw(false, setTimeout(() => {
            wx.canvasToTempFilePath({
              canvasId: 'canvas',
              destWidth: canvasWidth,
              destHeight: canvasHeight,
              success: function (res) {
                // console.log(res.tempFilePath)//最终图片路径
                resolve(res.tempFilePath)
               
              },
              fail: function (res) {
                console.log(res.errMsg)
              }
            })
          }, 100))
        },
        fail: function (res) {
          console.log(res.errMsg)
        },
      })
    })
  }
})


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值