vant使用Uploader 上传图片大小压缩

2,656 阅读2分钟

今天上传图片时候,接口既然对图片大小有要求

查看一波之后,发现 大佬nlh1996 写的vant图片大小处理之后简单明了。

自己整理一波

vant 的 Uploader组件事件

文件上传完毕后会触发after-read回调函数,获取到对应的file对象

我们可以从after-read回调函数中做拿到的file对象做处理

写个方法,把图片过大的处理一波

js
 
    /**canvasToLower把图片变小
     * imginClude64 图片不去头64编码
     * type 图片类型
     * size 图片大小
     */
    canvasToLower (imginClude64, type, size) {
    //因为onload是需要时间的,而且我接下的操作也是走请求,所以这里我们用异步去处理返回的结果
      return new Promise((resolve, reject) => {
        // 没有请求过,走请求
        // 先看图片长宽大小是不是超4m,最长边最多4096px
        var thisImg = new Image();
        thisImg.src = imginClude64;
        / 监听浏览器加载图片完成,然后进行绘制
        thisImg.onload = () => {
          if (thisImg.width > 4096 || size > 400000) { //这里就是上传图片的长了,或者大了
            // 创建canvas以及画布,把图片变小再说
            // 创建Canvas对象(画布)
            let canvas = document.createElement('canvas')
            // 获取对应的CanvasRenderingContext2D对象(画笔)
            let context = canvas.getContext('2d')
            // 把他的宽度变成1300,高度也也要等比例缩放。算出宽高
            canvas.width = 1300
            canvas.height = thisImg.height * canvas.width / thisImg.width
            //drawImage画布绘制的方法。
            context.drawImage(thisImg, 0, 0, canvas.width, canvasHeight)
            // let smallImg64 = canvas.toDataURL(type, 0.92)
            // type是组件中有的格式是image/jpeg的
            let smallImg64 = canvas.toDataURL('type', 1)

            let res = smallImg64.split(',')[1];
            resolve(res)
          } else {
            resolve('ok')
          }
        }
      })
    }

方法写好了,然后再,调用

let size = file.file.size
let type = file.file.type
await this.canvasToLower(file.content, type, size).then(res => {

              if (res === 'ok') {
                    <!-- 当图片ok的时候...-->
              } else {
                    <!--当图片不ok的时候做了处理,而且去了64编码的头-->
                    <!--直接把res拿去请求或者存起来在一起处理dbok-->
              }
            })
            

大概就是这样子,bai~