小程序上传图片之压缩图片并转base64

效果图:
压缩效果图
说明:当上传图片内存大于100kb时对图片进行压缩处理;

html:

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

<view class="upLoadPicBox">
  <view class="upLoadPicIconBox" wx:for="{{tempFilePathsList}}" wx:key="index">
    <image class="upLoadPicIcon" src="{{item.imgUrl}}" catchtap="upLoadPic" data-index="{{index}}"></image>
    <view class="delBtn" catchtap="delPic">删除</view>
  </view>
  <image class="upLoadPicIconBox" wx:if="{{tempFilePathsList.length<limitPicNum}}" src="/images/upLoadPic.png" catchtap="upLoadPic" data-index="add"></image>
</view>

css:

.upLoadPicBox{display: flex}
.upLoadPicIconBox{position: relative;margin-right: 20rpx;display: block;width: 160rpx;height: 160rpx;}
.delBtn{position: absolute;left: 0;bottom: 0;height: 40rpx;width: 100%;background: rgba(0, 0, 0, 0.5);color: white;text-align: center;font-size: 30rpx;line-height: 40rpx}
.upLoadPicIcon{display: block;width: 160rpx;height: 160rpx}
.submit{width: 100% !important;height: 100rpx;line-height: 100rpx;text-align: center;padding: 0;margin: 0;background: #008cd7;position: fixed;left: 0;bottom: 0;color: white;border-radius: 0;font-size: 36rpx;font-weight: normal}

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

js:

Component({
  properties: {
    picList: { // 默认图片
      type: Array,
      value: []
    },
    limitPicNum: { // 默认图片
      type: Number,
      value: []
    }
  },

  observers: {

  },

  data: {
    tempFilePathsList: [], //图片数组
    currentTempFilePath: '' //当前选中项的图片压缩后路径
  },

  ready() {

  },

  methods: {
    upLoadPic: function(e) {
      var that = this;
      var index = e.currentTarget.dataset.index;
      wx.chooseImage({
        count: 1,
        success: function(res) {
          let tempFilePathsList = that.data.tempFilePathsList;
          let tempFilePaths = res.tempFilePaths;
          if (res.tempFiles[0].size >= 100000) {
            that.getCanvasImg(0, 0, tempFilePaths);
            setTimeout(() => {
              tempFilePaths[0] = that.data.currentTempFilePath;
              that.imgFilter(index,tempFilePaths[0], tempFilePathsList)
              wx.hideLoading()
            }, 1200)
          }else{
            that.imgFilter(index,tempFilePaths[0], tempFilePathsList)
          }
        }
      })
    },

    //图片转base64后返给父级组件
    imgFilter: function (index,tempFileUrl, tempFilePathsList){
      var that = this
      let imageSplit = tempFileUrl.split('.');
      let imageType = imageSplit[imageSplit.length - 1];
      if (imageType == 'jpg') imageType = 'jpeg'; //***end***
      var baseUrl;
      wx.getFileSystemManager().readFile({
        filePath: tempFileUrl, //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => { //成功的回调
          baseUrl = `data:image/${imageType};base64,${res.data}`;
          let newArr = [];
          let newObj = {};
          newObj.baseUrl = baseUrl;
          newObj.imgUrl = tempFileUrl;
          newArr.push(newObj)
          if (index == 'add') {
            tempFilePathsList = [...tempFilePathsList, ...newArr];
          } else {
            tempFilePathsList.splice(index, 1, ...newArr)
          }
          that.setData({
            tempFilePathsList: tempFilePathsList
          })

          let myEventDetail = {
            imgList: that.data.tempFilePathsList
          };
          that.triggerEvent('imgList', myEventDetail);
        }
      })
    },

    //压缩并获取图片,这里用了递归的方法来解决canvas的draw方法延时的问题
    getCanvasImg: function(index, failNum, tempFilePaths) {
      wx.showLoading({
        title: '图片压缩中',
        mask: true,
      })
      var that = this;
      wx.getImageInfo({
        // src: tempFilePaths[index],// 用于多个图片压缩
        src: tempFilePaths[0], //图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径,  
        success: res => {
          // util.imageUtil  用语计算长宽比
          var imageSize = this.imageUtil(res);
          that.imageSize = imageSize;
          if (index < tempFilePaths.length) {
            var _this = this;
            let ctx = wx.createCanvasContext('attendCanvasId', _this);
            ctx.drawImage(tempFilePaths[index], 0, 0, imageSize.imageWidth, imageSize.imageHeight);
            setTimeout(() => {
              ctx.draw(true, setTimeout(() => {
                wx.canvasToTempFilePath({
                  canvasId: 'attendCanvasId',
                  x: 0,
                  y: 0,
                  destWidth: imageSize.imageWidth,
                  destHeight: imageSize.imageHeight,
                  fileType: 'jpg',
                  success: function success(res) {
                    that.setData({
                      currentTempFilePath: res.tempFilePath
                    })
                  },
                  fail: function(e) {
                    failNum += 1; //失败数量,可以用来提示用户
                    that.getCanvasImg(inedx, failNum, tempFilePaths);
                  }
                }, _this);
              }, 500))
            }, 300)
          }
        },
        fail: () => {},
        complete: () => {}
      });
    },


    imageUtil: function(e) {
      var that = this;
      var imageSize = {};
      var originalWidth = e.width; //图片原始宽  
      var originalHeight = e.height; //图片原始高  
      var originalScale = originalHeight / originalWidth; //图片高宽比  

      //获取屏幕宽高  
      wx.getSystemInfo({
        success: function(res) {
          // canvas 基础宽高调为 2 倍,避免图片压缩程度过高导致图片字体显示不清楚
          var windowWidth = res.windowWidth;
          var windowHeight = res.windowHeight;
          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;
          }
        }
      })

      that.setData({
        imageWidth: imageSize.imageWidth,
        imageHeight: imageSize.imageHeight
      })
      return imageSize;
    },

    //删除当前图片
    delPic: function(e) {
      let index = e.currentTarget.dataset.index;
      let tempFilePathsList = this.data.tempFilePathsList;
      tempFilePathsList.splice(index, 1)
      this.setData({
        tempFilePathsList
      })
    }
  }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值