下載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); } } }); }); }