微信小程序等比例图片压缩上传,100%可用,非官方压缩方法

本文目录

原理

  1. 微信小程序调用图片选择,获得图片地址
  2. 使用微信小程序获得图片信息宽和高
  3. 设置图片目标尺寸,根据压缩比例设置
  4. 创建 canvas 上下文,图片地址写入 canvas,
  5. 更新 canvas 尺寸,
  6. wx.canvasToTempFilePath 获得新的图片。最后将它上传到服务器即可

例子

index.wxml

<view bindtap='uploadImg'>上传</view>
 <image bindtap='uploadImg' data-number="0" src="{{ uploadPic[0] }}" alt=""mode="widthFix"></image>
<canvas style="width: {{cw}}px; height: {{ch}}px;" canvas-id="firstCanvas"></canvas>

如果不想要出现 canvas,可以设置如下

<canvas style="width: {{cw}}px; height: {{ch}}px;position: absolute; z-index: -1; left: -10000rpx;; top: -10000rpx;" canvas-id="firstCanvas"></canvas>

index.js

Page ({

  /**
   * 页面的初始数据
   */
  data: {
      cw: 300,
      ch: 200,
      uploadPic: [],
  },

  uploadImg (e) {
      let that = this;
      console.log (e);
      let index = e.currentTarget.dataset.number;
      let uploadFile = ''; // 最后处理完,图片上传的图片地址
      wx.chooseImage ({
          success (res) {
              console.log(res)
              const tempFilePaths = res.tempFilePaths;

              // 获得原始图片大小
              wx.getImageInfo ({
                  src: res.tempFilePaths[0],
                  success (res) {
                      // console.log ('获得原始图片大小',res.width)
                      //console.log (res.height)
                      var originWidth, originHeight;
                      originHeight = res.height;
                      originWidth = res.width;
                      console.log (originWidth);
                      // 压缩比例
                      // 最大尺寸限制
                      var maxWidth = 1200,
                          maxHeight = 600;
                      // 目标尺寸
                      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) => {
                  // 写入图片数组
                  var uploadpic = "uploadPic [" + index + "]";
                  //
                  that.setData ({
                    [uploadpic]: res.tempFilePath
                  });
                  uploadFile = res.tempFilePath;
                  // 保存到相册
                  // wx.saveImageToPhotosAlbum({
                  //   filePath: res.tempFilePath,
                  //   success: (res) => {
                  //     console.log (res)
                  //   },
                  //   fail: (err) => {
                  //     console.error (err)
                  //   }
                  // })
                  wx.uploadFile ({
                    url: 'https://example.weixin.qq.com/upload', // 仅为示例,非真实的接口地址
                    filePath: uploadFile,
                    name: 'file',
                    formData: {
                      'user': 'test'
                    },
                    success (res) {
                      const data = res.data
                      //do something
                    }
                  })
                },
                fail: (err) => {
                  console.error (err)
                }
              }, this)
                      });

                  }
              })

          }
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

评论区 (0)

没有记录
支持 markdown,图片截图粘贴拖拽都可以自动上传。

相关帖子

黑白课堂

如果你在.env文件下配置了变量参数,在路由缓存下会无效

| 最后更新 2020-12-11 03:05:43
3347 0
黑白课堂

laravel之Artisan命令操作,以及自己编写Artisan Console命令

| 最后更新 2021-01-13 14:24:58
3317 0
黑白课堂

JWT(JSON Web Token)是一个非常轻巧的规范。这个规范允许我们使用JWT在用户和服务器之间传递安全可靠的信息。 一个JWT实际上就是一个字符串,它由三部分组成,头部、载荷与签名

| 最后更新 2021-01-13 14:25:29
3301 0
黑白课堂

扩展一个指令在blade模板中使用。

| 最后更新 2020-12-11 03:04:51
2801 0
黑白课堂

所有Laravel应用启动的中心,所有Laravel的核心服务都是通过服务提供者启动,服务提供者是应用配置的中心. >这里需要了解下IOC(控制反转)也叫依赖注入

| 最后更新 2021-01-11 03:14:14
2886 0
黑白课堂

控制对资源的访问权限,这个权限不同于RBAC(角色的权限访问控制),比如,只能操作自己的信息,可以说是拟补RBAC的更加细腻的权限。

| 最后更新 2021-01-13 14:24:00
2798 0
黑白课堂

黑白课堂 · 技术专家

专业PHP开发

年度VIP 站长创业者玉树凌风每天醒来0收入
查看更多

最新视频课程