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

Android 相冊選圖後判斷圖片旋轉角度

編輯:關於 Android 程式設計

問題背景

在開發圖片合成、相冊選圖或相機相關功能時,常會遇到一個問題:使用者從相冊選擇圖片後,圖片在應用中顯示的方向可能與預期不同。這通常是因為照片本身包含 EXIF 方向資訊。

讀取 EXIF 方向

Android 可透過 ExifInterface 讀取圖片的 EXIF 資訊,再判斷 Orientation 屬性。

常見寫法如下:

ExifInterface exifInterface = new ExifInterface(path);

int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

判斷旋轉角度

可根據 orientation 對應到 0、90、180、270 度:

  • ORIENTATION_ROTATE_90:回傳 90。
  • ORIENTATION_ROTATE_180:回傳 180。
  • ORIENTATION_ROTATE_270:回傳 270。
  • 其他情況:回傳 0。

概念如下:

public static int readPictureDegree(String path) { ... }

應用方式

取得角度後,可在顯示或儲存前使用 Matrix 旋轉 Bitmap:

Matrix matrix = new Matrix();

matrix.postRotate(degree);

Bitmap rotatedBitmap = Bitmap.createBitmap(source, 0, 0, width, height, matrix, true);

這樣可以確保使用者看到的圖片方向正確,也能避免後續合成時出現方向錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved