在 App 裡使用相機拍攝的照片時,方向問題幾乎一定會遇到:同一張照片在不同裝置上可能一個橫一個豎。要正確呈現,就必須先讀出照片的朝向資訊,再決定要不要旋轉。以下示範以 ExifInterface 判斷並修正方向的完整做法。
/**
* 依指定路徑載入圖片並設定到 ImageView
*
* @param imgPath 手機圖片檔案路徑
* @param imgView 要設定的 ImageView
*/
public void setImg(String imgPath, ImageView imgView) {
File file = new File(imgPath);
if (file.exists() && file.canRead()) {
// ------- 1. 圖片縮放 -------
// 取得螢幕資訊
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int dw = metric.widthPixels; // 螢幕寬
int dh = metric.heightPixels; // 螢幕高
// 先只讀尺寸,不真正解碼
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
// 計算水平與垂直縮放係數
int heightRatio = (int) Math.ceil(options.outHeight / (float) dh);
int widthRatio = (int) Math.ceil(options.outWidth / (float) dw);
// 取較大者作為 sampling 倍率
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
options.inSampleSize = heightRatio;
} else {
options.inSampleSize = widthRatio;
}
}
// 正式解碼
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(imgPath, options);
// ------- 2. 判斷圖片朝向 -------
try {
ExifInterface exif = new ExifInterface(imgPath);
int degree = 0; // 需要旋轉的角度
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;
default:
break;
}
}
}
if (degree != 0) { // 需要旋轉
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preRotate(degree);
Bitmap mRotateBitmap = Bitmap.createBitmap(bitmap, 0, 0,
width, height, matrix, true);
imgView.setImageBitmap(mRotateBitmap);
} else {
imgView.setImageBitmap(bitmap);
}
} catch (IOException e) {
// 建議在此補上日誌,避免問題被靜默吞掉
}
}
}
掌握這套流程,相機照片的方向就能在各裝置上保持一致,使用者不會再遇到「躺著的照片」。