【发布时间】:2017-09-21 13:23:11
【问题描述】:
我一直在尝试将图像保存到Firebase Storage,但我注意到从图库/Google 云端硬盘保存的几乎所有图片都会旋转。(通常是 90 度)
阅读较早的帖子后,我意识到这是一个常见问题,我尝试通过尝试来自此 post 或来自此 one 、此 one 的解决方案来解决它,我可以继续。
大约 8 小时后,我终于决定在这里提问。 是否有更好、更简单的实现来阻止图像旋转?
我使用ExifInterface(始终返回 0)的最后一个(显然是不成功的)实现是这个:
选择图片
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
OnActivityResult
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
int rotateImageAngle = getPhotoOrientation(getContext(), selectedImage, filePath);
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), selectedImage);
// Log.d(TAG, String.valueOf(bitmap));
addPictureButton.setText("Done");
} catch (IOException e) {
e.printStackTrace();
}
if( bitmap != null)
{
RotateBitmap(bitmap , rotateImageAngle);
}
}
辅助方法
public int getPhotoOrientation(Context context, Uri imageUri, String imagePath){
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageUri, null);
File imageFile = new File(imagePath);
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Log.i("RotateImage", "Exif orientation: " + orientation);
Log.i("RotateImage", "Rotate value: " + rotate);
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
public static Bitmap RotateBitmap(Bitmap source, int angle)
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
注意:如果需要,我将添加将图像上传到 Firebase 的代码
【问题讨论】:
标签: android bitmap android-bitmap image-rotation