筆者在開發中有遇到過這樣的問題,就是在三星 note4手機上拍照,發現圖片是自動旋轉90度的,導致最後上傳的圖片是旋轉的,爲了解決這個問題,我們就需要先獲取圖片的旋轉度信息,然後再將圖片按照一定的角度旋轉過來,最後上傳以達到我們想要的效果
獲取圖片的旋轉度
/**
* 獲取圖片的旋轉度
*
* @param path 圖片的路徑
* @return 返回圖片的旋轉度
*/
public static int getBitmapDegree(String path) {
int degree = 0;
try {
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;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return degree;
}
將圖片旋轉一定的角度後返回
/**
* 將圖片旋轉一定的角度
*
* @param bm 需要旋轉的圖片
* @param degree 圖片旋轉的角度
* @return 旋轉後的圖片
*/
public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
Bitmap returnBm = null;
//根據旋轉角度生成對應的旋轉矩陣
Matrix matrix = new Matrix();
matrix.postRotate(degree);
try {
returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
} catch (Exception ex) {
ex.printStackTrace();
}
if (returnBm == null) {
returnBm = bm;
}
if (bm != returnBm) {
bm.recycle();
}
return null;
}