vue 上傳圖片進行壓縮圖片

李大蛋發表於2020-09-25
afterRead(file){
             if(this.fileList.length > 1){
                 this.fileList.splice(1);
                 this.$msg({
                     text:'只能選擇這麼多!',
                     type:'info'
                 })
                 return false;
             }
            
            let maxSize = 1 * 1024 * 1024;  //自己定義的檔案大小,超過多少M就開始壓縮(現在是1M)
            let fileObj = file.file;  // 當前的圖片
             if (fileObj.size > maxSize) {
                this.imgcompress(fileObj, file);
            }else{
                 //沒有大於1兆直接執行
                 let Files = this.Files;
                 Files.push(file.file);
            } 
        },
 imgcompress(file, files) {
    const img = document.createElement('img')
    const reader = new FileReader(); // 讀取檔案資源例項
    reader.readAsDataURL(file);   //讀取圖片資源
    reader.onload = e => {        //讀取成功
        img.src = e.target.result;
        const { width: originWidth, height: originHeight } = img; //上傳的圖片的寬高
        const maxWidth = 1000, //設定一個canvas 的最大寬高
        maxHight = 1000;
        if (originWidth > maxWidth || originHeight > maxHight) {
        //計算出圖片的縮放比例
        if (originWidth > originHeight) {
            //寬 大於 高
            const Proportion = Math.ceil(originWidth / maxWidth);
            let targetWidht = parseInt(originWidth / Proportion); //目標的寬度
            let targetHeight = parseInt(originHeight / Proportion); //目標的高度

            this.createCanvasCompress(targetWidht, targetHeight, img, files);
        } else {
            const Proportion = Math.ceil(originHeight / maxHight); //高大於寬
            let targetWidht = parseInt(originWidth / Proportion); //目標的寬度
            let targetHeight = parseInt(originHeight / Proportion); //目標的高度
            let bold = this.createCanvasCompress(
            targetWidht,
            targetHeight,
            img,
            files
            );
        }
    } else {
      let quality = 0.8;
      this.createCanvasCompress(
        originWidth,
        originHeight,
        img,
        files,
        quality
      );
    }
  };
},
 createCanvasCompress(targetWidth, targetHeight, img, files, quality) {
  let that = this;
  return new Promise((resolve, reject) => {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
    // 設定寬高度為等同於要壓縮圖片的尺寸
    canvas.width = targetWidth;
    canvas.height = targetHeight;
    context.clearRect(0, 0, targetWidth, targetHeight);
    //將img繪製到畫布上
    console.log(targetWidth, targetHeight);
    context.drawImage(img, 0, 0, targetWidth, targetHeight);

    let bold = canvas.toBlob(
      function(blob) {
        resolve(blob);
        that.Files.push(blob); //壓縮之後的圖片
        //拿到的是blob格式的圖片,需要把blob格式轉換為file格式
        let files1 = new window.File([blob], files.file.name, {type: files.file.type})
        console.log(files1 )
      },
      "image/png",
      quality
    );
  });
  // 建立畫布
},

相關文章