问题
Since android 10 there is some changes in accessing media files. After going through documentation https://developer.android.com/training/data-storage/shared/media i have been able to load the media content in to a bitmap, but i didn't get the orientation information. I know there is some restriction to the location information of the image, but does these exif restrictions also effect orientation information? If there is any other way to get an image's orientation information, please let me know. The code am using is given below (which is always returning 0 - Value for undefined). Thank you.
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);
}
回答1:
BitmapFactory.decodeStream
consumed the whole stream and closed it.
You should open a new stream first before trying to read the exif.
回答2:
Firstly, consider the API used in different SDK version, please use the AndroidX ExifInterface Library
Secondly, ExifInterface
for reading and writing Exif tags in various image file formats. Supported for reading: JPEG, PNG, WebP, HEIF, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW, RAF.
But you use it for bitmap, Bitmap does not have any EXIF headers. You already threw away any EXIF data when you loaded the Bitmap from wherever it came from. Use ExifInterface on the original source of the data, not the Bitmap
you can try to use the following code to get the info and remember to use the original stream.
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
}
}
来源:https://stackoverflow.com/questions/59606488/how-to-get-an-images-orientation-information-in-android-10