exif.js 實現圖片旋轉到正常


  下載exif.js
  npm install exif-js --save
  引入exif.js
  import EXIF from 'src/utils/exif-js';
//旋轉圖片到正常
const _rotateImg = (imgFile) => {
  return new Promise((resolve, reject) => {
    EXIF.getData(imgFile, function () {
      let exifTags = EXIF.getAllTags(this);
      let reader = new FileReader();
      reader.readAsDataURL(imgFile);
      reader.onload = e => {
        let imgData = e.target.result;
        // 8 表示 順時針轉了90
        // 3 表示 轉了 180
        // 6 表示 逆時針轉了90
        if (
          exifTags.Orientation == 8 ||
          exifTags.Orientation == 3 ||
          exifTags.Orientation == 6
        ) {
          //翻轉
          //獲取原始圖片大小
          const img = new Image();
          img.src = imgData;
          img.onload = function () {
            let cvs = document.createElement('canvas');
            let ctx = cvs.getContext('2d');
            //如果旋轉90
            if (
              exifTags.Orientation == 8 ||
              exifTags.Orientation == 6
            ) {
              cvs.width = img.height;
              cvs.height = img.width;
            } else {
              cvs.width = img.width;
              cvs.height = img.height;
            }
            if (exifTags.Orientation == 6) {
              //原圖逆時針轉了90, 所以要順時針旋轉90
              ctx.rotate(Math.PI / 180 * 90);
              ctx.drawImage(
                img,
                0,
                0,
                img.width,
                img.height,
                0,
                -img.height,
                img.width,
                img.height
              );
            }
            if (exifTags.Orientation == 3) {
              //原圖逆時針轉了180, 所以順時針旋轉180
              ctx.rotate(Math.PI / 180 * 180);
              ctx.drawImage(
                img,
                0,
                0,
                img.width,
                img.height,
                -img.width,
                -img.height,
                img.width,
                img.height
              );
            }
            if (exifTags.Orientation == 8) {
              //原圖順時針旋轉了90, 所以要你時針旋轉90
              ctx.rotate(Math.PI / 180 * -90);
              ctx.drawImage(
                img,
                0,
                0,
                img.width,
                img.height,
                -img.width,
                0,
                img.width,
                img.height
              );
            }
            resolve(cvs.toDataURL('image/png'));
          }
        }
        else {
          resolve(imgData);
        }
      }
    });
  });
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM