我正在嘗試拍攝照片並將位圖設置爲imageview。但是不同的設備產生的位圖旋轉方式不同。從設備到設備的Android圖像旋轉更改
一個是三星J5黃金(180度) 一個是LG G3(正常的,因爲我根據這個設備寫的代碼) 兩者都有的Android 6.0(實際是samsuung有6.0.1,但我不認爲這有什麼差別)
這是我的代碼:
private int findImageRotation(Uri uri) throws IOException {
ExifInterface ei = new ExifInterface(uri.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
int degree = 0;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
break;
}
return degree;
}
private Bitmap rotateImage(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
private void imageToBase64(final Uri uri, final Base64ConvertListener listener) {
new Handler().post(new Runnable() {
@Override
public void run() {
Bitmap bitmap;
try {
int degree = findImageRotation(uri);
bitmap = BitmapFactory.decodeStream(getContext().getContentResolver().openInputStream(uri));
bitmap = rotateImage(bitmap, degree - 90);
if (bitmap != null) {
String extension = getMimeType(getContext(), uri);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
if (extension.toLowerCase().contains("png"))
bitmap.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
else if (extension.toLowerCase().contains("jpg") || extension.toLowerCase().contains("jpeg"))
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
ivHostImage.setImageBitmap(bitmap);
byte[] byteArray = byteArrayOutputStream.toByteArray();
listener.onConvertedToBase64("data:" + extension + ";base64," + Base64.encodeToString(byteArray, Base64.DEFAULT));
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
謝謝,它的作品。也供將來參考,以獲得絕對路徑; [鏈接](http://stackoverflow.com/a/20559175/5973493) – msecilmis