微信小程序压缩图片并上传到服务器(拿去即用)

这里注意一下,图片压缩后的宽度是画布宽度的一半

canvasToTempFilePath 创建画布的时候会有一定的时间延迟容易失败,这里加setTimeout来缓冲一下

这是单张图片压缩,多张的压缩暂时还没有成功,保存到服务器上后是空白的,如有大神望指点一二(>人<;)
<canvas canvas-id='photo_canvas' style='width:1000rpx;height:{{canvas_h}}px' class='myCanvas'></canvas>

/**压缩图片 */
  compressionImage(tempFilePaths, params) {
    let that = this
    wx.getImageInfo({
      src: tempFilePaths[0],
      success: function(res) {
        var ctx = wx.createCanvasContext('photo_canvas');
        //设置canvas尺寸
        var towidth = 500; //按宽度500px的比例压缩
        var toheight = Math.trunc(500 * res.height / res.width);
        that.setData({
          canvas_h: toheight
        })
        ctx.drawImage(tempFilePaths[0], 0, 0, res.width, res.height, 0, 0, towidth, toheight)
        that.createMap(ctx, params);
      }
    })
  },
  /**创建画布并上传图片 */
  createMap(ctx, params) {
    let that = this;
    ctx.draw(true, function() {
      wx.showLoading({
        title: '压缩中',
      })
      setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'photo_canvas',
          fileType: "jpg",
          success: function(res) {
            wx.hideLoading();
            wx.uploadFile({
              url: app.globalData.baseUrl + '/wechat/want/addWant',
              filePath: res.tempFilePath,
              name: 'file',
              formData: {
                'parameters': JSON.stringify(params)
              },
              success: function(res) {
                console.log("state:" + JSON.parse(res.data).state)
                if (JSON.parse(res.data).state === 1) {
                  wx.showToast({
                    title: '发布成功',
                    duration: 2000,
                    icon: "none",
                    success() {
                      setTimeout(function() {
                        wx.navigateBack({
                          delta: 1,
                        })
                      }, 1000);
                    }
                  })
                }
              },
              fail(res) {
                console.log("fail" + res)
              }
            })
          },
          fail(res) {
            if (res.errMsg === "canvasToTempFilePath:fail:create bitmap failed") {
              console.log("导出map失败")
            }
          }
        }, this)
      }, 200);
 
    })
  },
posted @ 2019-03-17 23:28  不忘编码  阅读(4943)  评论(0编辑  收藏  举报