1. 程式人生 > >解決部分android手機照片被系統自動旋轉

解決部分android手機照片被系統自動旋轉

[size=medium]使用某星手機有為應用的相簿新增圖片時,發現照片已被旋轉,APP沒有做任何處理,因此肯定是手機在拍照儲存的時候做的手腳。[/size]

[size=medium]1、呼叫方法[/size]
int degree = ImageUtil.getBitmapDegree(imageInfo.getImgSourcePath());

if(0 != degree)
ImageUtil.rotateBitmapByDegree(arg2, degree);


[size=medium]2.具體程式碼[/size]
    /**
* 讀取圖片的旋轉的角度
*
* @param path
* 圖片絕對路徑
* @return 圖片的旋轉角度
*/
public static 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;
}
} catch (IOException e) {
e.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 (OutOfMemoryError e) {
}
if (returnBm == null) {
returnBm = bm;
}
if (bm != returnBm) {
bm.recycle();
bm = null;
}
return returnBm;
}