完美解決部分安卓手機呼叫系統拍照上傳時圖片旋轉問題
阿新 • • 發佈:2019-02-19
實際開發中我們經常會有拍照上傳圖片,或者上傳頭像的需求,但是經常會發現部分手機,例如三星等,拍照後的圖片會產生不同角度的旋轉,原因是這些手機拍照後會有一個自動旋轉的過程,具體解決思路也很簡單,我們來看下具體程式碼:
//首先我們先獲取當前圖片的旋轉角度
public static int readPictureDegree(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 (IOException e) {
e.printStackTrace();
}
return degree;
}
//然後我們再根據圖片的旋轉角度,給圖片進行相應角度的反向旋轉
public static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
if (bitmap == null)
return null;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}