最近在做專案的自定義相冊時,遇到了這么一個問題:從 小米9 手機上面的拉起系統相機進行拍照,然后上傳到服務器上面,發現圖片莫名其妙就旋轉了 90° ,這個并不符合業務方的需求,在仔細分析后,發現拍照后,系統保存到本地的照片已經給旋轉過了
因此要解決這個問題,就只有在拍照后,判斷圖片是否給旋轉,如果有,就將它旋轉回去
要獲取圖片的旋轉資訊,就需要獲取圖片的 Exit 資訊,它里面存盤了圖片的全部引數,我們可以通過 ExifInterface 來獲取到這個資料:
/**
* 讀取圖片的旋轉的角度
*
* @param path 圖片路徑
*
* @return 圖片的旋轉角度
*/
private int getBitmapDegree(String path) {
int degree = 0;//被旋轉的角度
try {
// 從指定路徑下讀取圖片,并獲取其 Exif 資訊
ExifInterface exifInterface = new ExifInterface(path);
// 獲取圖片的旋轉資訊
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
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;
}
} catch (IOException ignore) {
}
return degree;
}
如果 degree 不為 0 ,那么就說明 圖片已經給旋轉了,那么就需要我們去旋轉回去:
/**
* @param filePath 檔案存盤路徑
* @param degree 旋轉角度
* @param savePath 檔案保管路徑
*/
private void rotateBitmapByDegree(String filePath, int degree, String savePath) {
try {
Matrix matrix = new Matrix();
// 根據旋轉角度,生成旋轉矩陣
matrix.postRotate(degree);
Bitmap bm = BitmapFactory.decodeFile(filePath);
// 將原始圖片按照旋轉矩陣進行旋轉,并得到新的圖片
final Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
//將新的圖片保管到本地
bitmap.compress(CompressFormat.JPEG, 85, new FileOutputStream(savePath));
} catch (FileNotFoundException ignore) {
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/231019.html
標籤:其他
