數碼照片Exif - Orientation 自動修正解決方案

使用Canvas + exif-js自動修正數碼照片

使用場景,在作朋友圈 H5 時,時常遇到須要用戶拍照上傳圖片需求,可是在一些手機(iso)上拍出來的照片會出現奇怪的旋轉角度來呈現。通過各類百度才發現相機拍出來的圖片擁有不少屬性,其中一項是Orientation ,用於記錄拍攝時相機物理旋轉角度,例如把相機倒過來Orientation3,順時針豎起來Orientation6,逆時針豎起來Orientation8,正常模式Orientation1。根據這個屬性咱們能夠使用Canvas來對圖片重繪。css

Orientation 示意圖

sadas

Show Code

import EXIF from 'exif-js'; // 引入依賴插件

// 參數列表:img 對象,callback返回Base64圖片編碼,生成圖片質量默認值0.9
export const FixImg = (img, callback, quality = 0.9) => {
    
  let Orientation, ctxWidth, ctxHeight, base64; // 定義所需變量

  EXIF.getData(img, function() {
    Orientation = EXIF.getTag(this, 'Orientation');
    ctxWidth = this.naturalWidth;
    ctxHeight = this.naturalHeight;
    
    console.log(Orientation, ctxWidth, ctxHeight);

    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    canvas.width = ctxWidth;
    canvas.height = ctxHeight;
    if ([5, 6, 7, 8].includes(Orientation)) {
      canvas.width = ctxHeight;
      canvas.height = ctxWidth;
    }

    switch (Orientation) {
      case 2:
        ctx.transform(-1, 0, 0, 1, ctxWidth, 0);
        break;
      case 3:
        ctx.transform(-1, 0, 0, -1, ctxWidth, ctxHeight);
        break;
      case 4:
        ctx.transform(1, 0, 0, -1, 0, ctxHeight);
        break;
      case 5:
        ctx.transform(0, 1, 1, 0, 0, 0);
        break;
      case 6:
        ctx.transform(0, 1, -1, 0, ctxHeight, 0);
        break;
      case 7:
        ctx.transform(0, -1, -1, 0, ctxHeight, ctxWidth);
        break;
      case 8:
        ctx.transform(0, -1, 1, 0, 0, ctxWidth);
        break;
      default:
        ctx.transform(1, 0, 0, 1, 0, 0);
    }

    ctx.drawImage(img, 0, 0, ctxWidth, ctxHeight);
    
    // 默認輸出jpeg,也能夠讀取原圖片格式,最後輸出原圖格式,搜索關鍵詞 :File.type
    base64 = canvas.toDataURL('image/jpeg', quality); 
    callback(base64);
  });
};

性感照騙,在線修復: http://peichenhu.cn/demo/awesome/#/Exifhtml


相關補充:從圖片 Exif 信息中取到 Orientation 後,就能夠根據它來自動旋轉圖片了,canvas、filter 濾鏡、vml、css3 均可以實現圖片的旋轉。
參考文章:https://imququ.com/post/how-t...css3

相關文章
相關標籤/搜索