Vue實現(xiàn)剪切板圖片壓縮功能

監(jiān)聽剪切板粘貼事件,讀取剪切板中的圖片文件,轉(zhuǎn)成base64通過img標(biāo)簽顯示出來,此時可能會存在剪切板中圖片過大,產(chǎn)生上傳速度慢問題,接下來就跟大家分享下如何將base64圖片進行壓縮。先跟大家展示下最終實現(xiàn)的效果:

公司主營業(yè)務(wù):成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計、移動網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)推出瑞昌免費做網(wǎng)站回饋大家。

Vue實現(xiàn)剪切板圖片壓縮功能

實現(xiàn)思路

  • 監(jiān)聽剪切板粘貼事件
  • 從事件回調(diào)中獲取clipboardData中的image對象聲明一個變量接收該對象
  • 使用reader.readAsDataURL方法加載clipboardData中的image對象
  • 在reader.onload回調(diào)中獲取圖片base64碼
  • 創(chuàng)建Image對象,賦值圖片base64碼至當(dāng)前對象的src屬性
  • 調(diào)用Image對象的onload函數(shù),獲取圖片寬高等信息
  • 聲明canvas畫布寬高分別為當(dāng)前圖片寬高除以縮放比例的值
  • 使用drawImage方法繪制當(dāng)前圖片

實現(xiàn)過程

本篇文章主要講解剪切板圖片壓縮的實現(xiàn),效果圖中如何將剪切板的圖片插入可編輯div以及如何發(fā)送,請移步我的另一篇文章: Vue解析剪切板圖片并實現(xiàn)發(fā)送功能

監(jiān)聽剪切板粘貼事件: 實現(xiàn)圖片粘貼

const that = this;
  document.body.addEventListener('paste', function (event) {
    that.$fullScreenLoading.show("讀取圖片中");
    // 獲取當(dāng)前輸入框內(nèi)的文字
    const oldText = that.$refs.msgInputContainer.textContent;
    // 讀取圖片
    let items = event.clipboardData && event.clipboardData.items;
    let file = null;
    if (items && items.length) {
      // 檢索剪切板items
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          file = items[i].getAsFile();
          break;
        }
      }
    }
    // 預(yù)覽圖片
    const reader = new FileReader();
    reader.onload = function(event) {
      // 圖片內(nèi)容
      const imgContent = event.target.result;
      // 創(chuàng)建img標(biāo)簽
      let img = document.createElement('img');//創(chuàng)建一個img
      // 獲取當(dāng)前base64圖片信息,計算當(dāng)前圖片寬高以及壓縮比例
      let imgObj = new Image();
      let imgWidth = "";
      let imgHeight = "";
      let scale = 1;
      imgObj.src = imgContent;
      imgObj.onload = function() {
        // 計算img寬高
        if(this.width<400){
          imgWidth = this.width;
          imgHeight = this.height;
        }else{
          // 輸入框圖片顯示縮小10倍
          imgWidth = this.width/10;
          imgHeight = this.height/10;
          // 圖片寬度大于1920,圖片壓縮5倍
          if(this.width>1920){
            // 真實比例縮小5倍
            scale = 5;
          }
        }
        // 設(shè)置可編輯div中圖片寬高
        img.width = imgWidth;
        img.height = imgHeight;
        // 壓縮圖片,渲染頁面
        that.compressPic(imgContent,scale,function (newBlob,newBase) {
          // 刪除可編輯div中的圖片名稱
          that.$refs.msgInputContainer.textContent = oldText;
          img.src = newBase; //設(shè)置鏈接
          // 圖片渲染
          that.$refs.msgInputContainer.append(img);
          that.$fullScreenLoading.hide();
        });
      };
    };
    reader.readAsDataURL(file);
  });

實現(xiàn)base64圖片壓縮函數(shù)

// 參數(shù): base64地址,壓縮比例,回調(diào)函數(shù)(返回壓縮后圖片的blob和base64)
  compressPic:function(base64, scale, callback){
    const that = this;
    let _img = new Image();
    _img.src = base64;
    _img.onload = function() {
      let _canvas = document.createElement("canvas");
      let w = this.width / scale;
      let h = this.height / scale;
      _canvas.setAttribute("width", w);
      _canvas.setAttribute("height", h);
      _canvas.getContext("2d").drawImage(this, 0, 0, w, h);
      let base64 = _canvas.toDataURL("image/jpeg");
      // 當(dāng)canvas對象的原型中沒有toBlob方法的時候,手動添加該方法
      if (!HTMLCanvasElement.prototype.toBlob) {
        Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
          value: function (callback, type, quality) {
            let binStr = atob(this.toDataURL(type, quality).split(',')[1]),
              len = binStr.length,
              arr = new Uint8Array(len);
            for (let i = 0; i < len; i++) {
              arr[i] = binStr.charCodeAt(i);
            }
            callback(new Blob([arr], {type: type || 'image/png'}));
          }
        });
      }else{
        _canvas.toBlob(function(blob) {
          if(blob.size > 1024*1024){
            that.compressPic(base64, scale, callback);
          }else{
            callback(blob, base64);
          }
        }, "image/jpeg");
      }
    }
  }

上述代碼github地址: chat-system

總結(jié)

以上所述是小編給大家介紹的Vue實現(xiàn)剪切板圖片壓縮功能,希望對大家有所幫助!

文章題目:Vue實現(xiàn)剪切板圖片壓縮功能
文章出自:http://muchs.cn/article4/pdjsoe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、網(wǎng)站策劃、做網(wǎng)站、關(guān)鍵詞優(yōu)化、定制網(wǎng)站、商城網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設(shè)計