You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MediaStore.Images.Media.getBitmap导致竖图旋转为横图的问题求助

解决竖图获取后被旋转为横图的问题

问题根源在于MediaStore.Images.Media.getBitmap()会忽略图片的EXIF旋转信息。很多竖拍的照片,实际像素存储是横屏尺寸(比如1280*720),但EXIF里标记了需要旋转90度才能正确显示。RecyclerView展示时系统会自动读取EXIF调整方向,但直接用这个方法获取的Bitmap是原始像素尺寸,没有应用旋转,导致方向错误。

以下是具体解决步骤:

1. 获取图片的EXIF旋转角度

编写方法读取图片的EXIF旋转信息:

private int getExifRotationAngle(Uri imageUri) throws IOException {
    ExifInterface exif = null;
    // 适配Android 7.0及以上版本
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        try (InputStream inputStream = getActivity().getContentResolver().openInputStream(imageUri)) {
            exif = new ExifInterface(inputStream);
        }
    } else {
        exif = new ExifInterface(imageUri.getPath());
    }
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            return 90;
        case ExifInterface.ORIENTATION_ROTATE_180:
            return 180;
        case ExifInterface.ORIENTATION_ROTATE_270:
            return 270;
        default:
            return 0;
    }
}

2. 根据旋转角度修正Bitmap

编写方法旋转Bitmap到正确方向:

private Bitmap rotateBitmap(Bitmap bitmap, int rotationAngle) {
    if (rotationAngle == 0) {
        return bitmap;
    }
    Matrix matrix = new Matrix();
    matrix.postRotate(rotationAngle);
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}

3. 替换原代码逻辑

替换你原来的getBitmap调用,加入旋转修正:

// 原代码:
// bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uris.get(i));

// 修改后:
Bitmap originalBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uris.get(i));
int rotation = getExifRotationAngle(uris.get(i));
bitmap = rotateBitmap(originalBitmap, rotation);
// 记得回收原Bitmap避免内存泄漏
originalBitmap.recycle();

额外推荐:使用ImageDecoder替代废弃的getBitmap

MediaStore.Images.Media.getBitmap()已被官方废弃,推荐使用ImageDecoder获取Bitmap,它默认会自动处理EXIF旋转:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    ImageDecoder.Source source = ImageDecoder.createSource(getActivity().getContentResolver(), uris.get(i));
    bitmap = ImageDecoder.decodeBitmap(source);
} else {
    // 兼容低版本,使用上面的EXIF处理逻辑
    Bitmap originalBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uris.get(i));
    int rotation = getExifRotationAngle(uris.get(i));
    bitmap = rotateBitmap(originalBitmap, rotation);
    originalBitmap.recycle();
}

这样处理后,获取到的Bitmap就会和RecyclerView展示的方向一致,竖图不会被转为横图。

内容的提问来源于stack exchange,提问作者Naresh Pradhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 11:36:05