笔者在开发中有遇到过这样的问题,就是在三星 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;
}