小程序 压缩图片并上传

mpvue 环境

首先放入 canvas ,这里 imageSize 用来自定义压缩后的图片大小,以便通过计算保持长宽比,计算方法下面会说,同时也可以通过修改长宽来自定义图片的大小避免压缩程度过大导致图片文字看不清楚。

放入 img,设置点击事件未 takePhoto

    <canvas canvas-id='attendCanvasId' class='myCanvas' :style="'width:' + imageSize.imageWidth + 'px; height:' + imageSize.imageHeight  + 'px;'"></canvas>

<img :src="userAvatar" alt @click="takePhoto">

import 引入 计算长宽比的JS (内容在下面)  ,并在 data 中声明一下 imageSize 变量,写入JS,可上传多个图片,这里我只压缩了一张,有多张的需求可以适当修改下代码

import util from "../util/util.js"; // 长宽比计算



data() {
    return {
      userAvatar: '', // 图片路径
      imageSize: ''
    };
  },

methods: {
    // 点击加_压缩
    takePhoto: function () {
      var that = this;
      // let imgViewList = that.data.imgViewList; //这个是用来承载页面循环展示图片的
        //拍照、从相册选择上传
        wx.chooseImage({
          count: 1,    //这个是上传的最大数量,默认为9
          sizeType: ['compressed'],    //这个可以理解为上传的图片质量类型(官方给的),虽然没什么卵用,要不然还要我们自己写压缩做什么
          sourceType: ['album', 'camera'],    //这个是图片来源,相册或者相机
          success: function (res) {
            var tempFilePaths = res.tempFilePaths    //这个是选择后返回的图片列表
            that.getCanvasImg(0, 0, tempFilePaths);    //进行压缩
          } 
        });
    },
    //压缩并获取图片,这里用了递归的方法来解决canvas的draw方法延时的问题
    getCanvasImg: function (index,failNum, tempFilePaths){
      var that = this;
      wx.getImageInfo({
        // src: tempFilePaths[index],// 用于多个图片压缩
        src: tempFilePaths[0], //图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径,  
        success: res => {
          // console.log(res)
          // util.imageUtil  用语计算长宽比
          var imageSize = util.imageUtil(res);
          console.log(imageSize)
          that.imageSize = imageSize;

          if (index < tempFilePaths.length){
            const ctx = wx.createCanvasContext('attendCanvasId');
            setTimeout(() => {
              ctx.drawImage(tempFilePaths[index], 0, 0, imageSize.imageWidth, imageSize.imageHeight);
              ctx.draw(true, function () {
                index = index + 1;//上传成功的数量,上传成功则加1
                wx.canvasToTempFilePath({
                  canvasId: 'attendCanvasId',
                  success: function success(res) {
                    that.uploadCanvasImg(res.tempFilePath);
                    // that.getCanvasImg(index,failNum,tempFilePaths); // 用于多个图片压缩
                  }, fail: function (e) {
                    failNum += 1;//失败数量,可以用来提示用户
                    that.getCanvasImg(inedx,failNum,tempFilePaths);
                  }
                });
              });
            }, 1000);
          }
        },
        fail: () => {},
        complete: () => {}
      });
    },
    //上传图片
    uploadCanvasImg: function (canvasImg){
      var that = this;
      var tempImg = canvasImg;
      wx.uploadFile({
            url: uploadhttpurl, // 仅为示例,非真实的接口地址
            filePath: tempImg,
            name: "file",
            success: res => {
              that.userAvatar = res.data.result;
            }
          });
    }

}

util.js  中计算长宽比

function imageUtil(e) {
    var imageSize = {};
    var originalWidth = e.width;//图片原始宽  
    var originalHeight = e.height;//图片原始高  
    var originalScale = originalHeight / originalWidth;//图片高宽比  
    
    console.log('原始宽: ' + originalWidth)
    console.log('原始高: ' + originalHeight)
    console.log('宽高比' + originalScale)
    //获取屏幕宽高  
    wx.getSystemInfo({
      success: function (res) {
        // canvas 基础宽高调为 2 倍,避免图片压缩程度过高导致图片字体显示不清楚
        var windowWidth = res.windowWidth * 2;
        var windowHeight = res.windowHeight * 2;
        var windowscale = windowHeight / windowWidth;//屏幕高宽比  
        
        // 图片尺寸大于设备
        if (originalWidth > res.windowWidth || originalHeight > res.windowHeight) {
          if (originalScale < windowscale) {//图片高宽比小于屏幕高宽比  
            //图片缩放后的宽为屏幕宽  
            imageSize.imageWidth = windowWidth;
            imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth;
          } else {//图片高宽比大于屏幕高宽比
            //图片缩放后的高为屏幕高  
            imageSize.imageHeight = windowHeight;
            imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight;
          }
        } else {
          imageSize.imageHeight = originalHeight;
          imageSize.imageWidth = originalWidth;
        }
      }
    })
    console.log('缩放后的宽: ' + imageSize.imageWidth)
    console.log('缩放后的高: ' + imageSize.imageHeight)
    return imageSize;
  }
  
module.exports = {
    imageUtil: imageUtil
  } 

此外还要这是一下 css,以便隐藏 canvas,避免显示错误 

.myCanvas {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

完成

 

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值