vant ,vue 圖片上傳壓縮

問題:解決vant圖片上傳太大 需要進行壓縮 (PS: 我寫了幾個方法,這裏我貼出主要得代碼 用//*** *** 標識 爲重點)

1.圖片壓縮得方法

  /**
     * 壓縮圖片方法
     * @param base64  ----baser64文件
     * @param scale ----壓縮比例 畫面質量0-9,數字越小文件越小畫質越差
     */
    compressImg (base64, scale) {
      let that = this
      // 處理縮放,轉換格式
      // 下面的註釋就不寫了,就是new 一個圖片,用canvas來壓縮
      const img = new Image()
      let blob
      img.src = base64
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      canvas.setAttribute('width', img.width + '')
      canvas.setAttribute('height', img.height + '')
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
      // 轉成base64 文件
      let imgType = base64.split(';')[0].split(':')[1]
      base64 = canvas.toDataURL(imgType)
      while (base64.length > that.maxSize) {
        scale -= 0.01 // *** 每次壓縮減少的比例爲0.01 ***
        base64 = canvas.toDataURL(imgType, scale)/*** 核心代碼通過canvas去壓縮 ***
      }
      // baser64 TO blob
      const arr = base64.split(',')
      const bytes = atob(arr[1])
      const bytesLength = bytes.length
      const u8arr = new Uint8Array(bytesLength)
      for (let i = 0; i < bytes.length; i++) {
        u8arr[i] = bytes.charCodeAt(i)
      }
      blob = new Blob([u8arr], {type: imgType})
      return blob
    },

2. 文件上傳

 

updatePics (files) {
  let that = this
  let fileArray = []
  if (files instanceof Array) { //  兼容單個圖片
    fileArray = files
  } else {
    fileArray.push(files)
  }
  this.filesShow.push(...fileArray) // 數組拼接
  let params = new FormData() // 創建form對象
  for (let i = 0; i < fileArray.length; i++) {
    let fileObj = fileArray[i].file
    if (fileObj.size > that.maxSize) { //*** 這邊我設置得是 maxSize 爲1024*1024*1 :1M ***
      let File = that.compressImg(fileArray[i].content, that.scale)
      params.append('file', File, fileObj.name) //  *** 這邊可以設置文件名稱或者格式 ***
    } else {
      params.append('file', fileObj) // 表單提交多個file
    }
  }
  this.$http({
    url: this.$http.adornUrl('/sys/file/uploadFile'),
    method: 'post',
    data: params
  }).then(({data}) => {
    if (data && data.code === 0) {
      this.fileIds.push(...data.data.fileIds)
      this.filePaths.push(...data.data.filePaths)
    } else {
      this.$toast(data.msg)
    }
  })
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章