vue 2移動端アップロード、プレビュー、圧縮画像、写真回転問題解決

6484 ワード

最近、モバイル端末がアバターをアップロードする需要があるため、バックグラウンドにアップロードされたデータはbase 64ビットで、その中でユーザー体験を高めるために、比較的大きな画像をcanvasで圧縮してからアップロードします.モバイル側で撮影機能を呼び出すと、画像が回転し、この問題を解決するためにexifを導入して撮影時の情報を判断して画像を処理するのが良いプラグインです.exifについてjsは彼のGitHubに行って理解することができて、こちらは直接npm install exif-js--saveインストールして、それからimportはすぐに使用することができます.以下はソースコードで、直接使用できます.



import Exif from 'exif-js'

export default {
  data () {
    return {
      headerImage:'',picValue:''
    }
  },
  mounted () {
  },
  methods: {
    upload (e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.picValue = files[0];
      this.imgPreview(this.picValue);
    },
    imgPreview (file) {
      let self = this;
      let Orientation;
      //         ,            
      Exif.getData(file, function(){
          Orientation = Exif.getTag(this, 'Orientation');
      });
      //       FileReader
      if (!file || !window.FileReader) return;

      if (/^image/.test(file.type)) {
          //     reader
          let reader = new FileReader();
          //    2    base64   
          reader.readAsDataURL(file);
          //         
          reader.onloadend = function () {
            let result = this.result;
            let img = new Image();
            img.src = result;
            //        100K,      ,      
            if (this.result.length <= (100 * 1024)) {
              self.headerImage = this.result;
              self.postImg();
            }else {
              img.onload = function () {
                let data = self.compress(img,Orientation);
                self.headerImage = data;
                self.postImg();
              }
            }
          } 
        }
      },
      postImg () {
        //     
      },
      rotateImg (img, direction,canvas) {
        //         ,    4           
        const min_step = 0;    
        const max_step = 3;      
        if (img == null)return;    
        //img         img       ,         
        let height = img.height;    
        let width = img.width;      
        let step = 2;    
        if (step == null) {    
            step = min_step;    
        }    
        if (direction == 'right') {    
            step++;    
            //      ,          
            step > max_step && (step = min_step);    
        } else {    
            step--;    
            step < min_step && (step = max_step);    
        }     
        //               
        let degree = step * 90 * Math.PI / 180;    
        let ctx = canvas.getContext('2d');    
        switch (step) {    
          case 0:    
              canvas.width = width;    
              canvas.height = height;    
              ctx.drawImage(img, 0, 0);    
              break;    
          case 1:    
              canvas.width = height;    
              canvas.height = width;    
              ctx.rotate(degree);    
              ctx.drawImage(img, 0, -height);    
              break;    
          case 2:    
              canvas.width = width;    
              canvas.height = height;    
              ctx.rotate(degree);    
              ctx.drawImage(img, -width, -height);    
              break;    
          case 3:    
              canvas.width = height;    
              canvas.height = width;    
              ctx.rotate(degree);    
              ctx.drawImage(img, -width, 0);    
              break;
        }    
    },
    compress(img,Orientation) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext('2d');
        //  canvas
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      //           ,           400   
      let ratio;
      if ((ratio = width * height / 4000000) > 1) {
        console.log("  400   ")
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
  //           
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      //        100        
      let count;
      if ((count = width * height / 1000000) > 1) {
        console.log("  100W  ");
        count = ~~(Math.sqrt(count) + 1); //          
  //                      
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      //  ios              
      if(Orientation != "" && Orientation != 1){
        switch(Orientation){
          case 6://     (  )90   
              this.rotateImg(img,'left',canvas);
              break;
          case 8://     (  )90   
              this.rotateImg(img,'right',canvas);
              break;
          case 3://  180   
              this.rotateImg(img,'right',canvas);//   
              this.rotateImg(img,'right',canvas);
              break;
        }
      }
      //      
      let ndata = canvas.toDataURL('image/jpeg', 0.1);
      console.log('   :' + initSize);
      console.log('   :' + ndata.length);
      console.log('   :' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    },
  }
}