Android中ImagePicker/MediaStore返回旋转图片问题求助
解决Content Uri获取Bitmap的旋转问题
不用纠结把content://Uri转成真实路径,直接通过ContentResolver打开输入流读取Exif旋转信息即可,这是适配所有系统(包括MIUI)的可靠方案:
步骤1:读取图片的Exif旋转角度
通过输入流直接读取图片的Exif元数据,无需真实路径:
private int getExifRotation(Context context, Uri uri) { int rotation = 0; try (InputStream inputStream = context.getContentResolver().openInputStream(uri)) { if (inputStream == null) return rotation; // 低版本(API<24)请用androidx.exifinterface.media.ExifInterface ExifInterface exif = new ExifInterface(inputStream); int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotation = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotation = 270; break; } } catch (IOException e) { e.printStackTrace(); } return rotation; }
步骤2:根据旋转角度修正Bitmap
获取到旋转角度后,对原始Bitmap进行旋转处理:
private Bitmap rotateBitmap(Bitmap bitmap, int rotation) { if (rotation == 0 || bitmap == null) return bitmap; Matrix matrix = new Matrix(); matrix.postRotate(rotation); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); }
整合使用示例
把两个方法结合到你的业务代码中:
// 你的content://格式图片Uri Uri imageUri = Uri.parse("content://com.android.providers.media.documents/document/image%3A3553763"); Bitmap originalBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri); int rotation = getExifRotation(this, imageUri); Bitmap rotatedBitmap = rotateBitmap(originalBitmap, rotation); // 记得回收原始Bitmap避免内存泄漏 if (originalBitmap != null && !originalBitmap.isRecycled()) { originalBitmap.recycle(); } // 现在使用rotatedBitmap即可
关键注意事项
- 低版本兼容:如果你的App需要兼容API 24以下的设备,必须引入AndroidX的ExifInterface库,在build.gradle中添加依赖:
然后代码中替换为implementation "androidx.exifinterface:exifinterface:1.3.6"androidx.exifinterface.media.ExifInterface - 内存优化:
MediaStore.Images.Media.getBitmap在处理大图片时容易触发OOM,建议改用BitmapFactory.decodeStream配合BitmapFactory.Options进行采样缩放,再执行旋转操作 - 系统适配:这种通过输入流读取Exif的方式直接操作图片原始数据,不会受MIUI等定制系统的媒体Provider路径封装影响,比通过路径读取Exif更稳定
内容的提问来源于stack exchange,提问作者Exitron
相关产品推荐
相关产品推荐

