android10如何获取图片的方向信息?

How to get an image's orientation information in android 10?

自 android10 起,访问媒体文件发生了一些变化。通过文档 https://developer.android.com/training/data-storage/shared/media 我已经能够将媒体内容加载到位图中,但我没有获得方向信息。我知道对图像的位置信息有一些限制,但是这些 exif 限制是否也会影响方向信息?如果有任何其他方法可以获取图像的方向信息,请告诉我。下面给出了我使用的代码(它总是返回 0 - 未定义的值)。谢谢。

ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(selectedFileUri)) {
 loadedBitmap = BitmapFactory.decodeStream(stream);
 ExifInterface exif = new ExifInterface(stream);
 orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
}

首先考虑API用于不同的SDK版本,请使用AndroidX ExifInterface Library

其次,ExifInterface用于读写各种图像文件格式的Exif标签。支持阅读:JPEG、PNG、WebP、HEIF、DNG、CR2、NEF、NRW、ARW、RW2、ORF、PEF、SRW、RAF。

但是你把它用于位图,位图没有任何EXIF headers。当您从任何地方加载位图时,您已经丢弃了所有 EXIF 数据。在原始数据源上使用 ExifInterface,而不是 Bitmap

您可以尝试使用以下代码获取信息,记得使用原始流

public static int getExifRotation(Context context, Uri imageUri) throws IOException {
    if (imageUri == null) return 0;
    InputStream inputStream = null;
    try {
        inputStream = context.getContentResolver().openInputStream(imageUri);
        ExifInterface exifInterface = new ExifInterface(inputStream);
        int orienttation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
        switch (orienttation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                return 90;
            case ExifInterface.ORIENTATION_ROTATE_180:
                return 180;
            case ExifInterface.ORIENTATION_ROTATE_270:
                return 270;
            default:
                return ExifInterface.ORIENTATION_UNDEFINED;
        }
    }finally {
       //here to close the inputstream
    }
}

BitmapFactory.decodeStream 消耗了整个流并关闭了它。

您应该先打开一个新流,然后再尝试读取 exif。