Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 讀取圖片的旋轉角度:用 ExifInterface 修正方向

編輯:關於 Android 程式設計

用手機拍攝的相片,其實際像素方向與顯示方向常常不同。相機為了省下實體旋轉的時間,會把方向資訊寫進 EXIF 中,由檢視程式負責旋正。若你自己解碼 Bitmap 卻沒讀這項資訊,就會出現「照片躺著」的經典問題。

程式碼

public static int getExifOrientation(String filepath) {
    int degree = 0;
    ExifInterface exif = null;
    try {
        exif = new ExifInterface(filepath);
    } catch (IOException ex) {
        Log.d(TAG, "cannot read exif " + ex);
    }

    if (exif != null) {
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
        if (orientation != -1) {
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        }
    }
    return degree;
}

取得角度之後怎麼用

拿到 degree 後,用 Matrix 對 Bitmap 做旋轉:

Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap corrected = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

或者設定在 BitmapFactory.Options 上,讓解碼時直接套用(API 10 以上):

BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
// 搭配 ExifInterface 取得的 degree 後,再以 Matrix 旋轉

幾個實務重點

  • ExifInterface 的兩種建構子:字串路徑版本需要 android.permission.READ_EXTERNAL_STORAGE(Android 11 之後還需 READ_MEDIA_IMAGES);若資料來源是串流,可改用 ExifInterface(InputStream)(API 24 以上)。
  • ORIENTATION_FLIP_* 系列:EXIF 除了旋轉,還有水平/垂直翻轉的標記。範例只處理了旋轉的三種情況,實務上若要完整支援,應一併處理 FLIP_HORIZONTAL、FLIP_VERTICAL 與 TRANSPOSE、TRANSVERSE,否則部分後製過的照片仍會方向錯誤。
  • Context 版本的 ExifInterface:AndroidX 提供了 androidx.exifinterface.media.ExifInterface,相容性比 framework 版本好得多,能在 API 低於 24 的環境讀取串流,建議優先採用。
  • 縮圖也要處理:上傳或產生縮圖時,務必先旋正再縮放,否則伺服器收到的會是躺倒的圖。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved