Background: I am writing a camera app for a messenger program. I cannot save the captured image to persistent disk at any time. The camera must support all orientations.
If you want a way to read EXIF data that wont be so dependent on where your URI came from you you could use the exif support library and read it from a stream. For example this is how I get the orientation of the image.
build.gradle
dependencies {
...
compile "com.android.support:exifinterface:25.0.1"
...
}
Example code:
import android.support.media.ExifInterface;
...
try (InputStream inputStream = context.getContentResolver().openInputStream(uri)) {
ExifInterface exif = new ExifInterface(inputStream);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
} catch (IOException e) {
e.printStackTrace();
}
The reason I had to do it this way once we started targeting api 25 (maybe a problem on 24+ also) but still supporting back to api 19, on android 7 our app would crash if I passed in a URI that was just referencing a file. Hence I had to create a URI to pass to the camera intent like this.
FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileprovider", tempFile);
The issue there is that file its not possible to turn the URI into a real file path (other than holding on to the temp file path).
If you have a content://
type of Uri
, android provides APIs through ContentResolver
and there’s no need to use external libraries:
public static int getExifAngle(Context context, Uri uri) {
int angle = 0;
Cursor c = context.getContentResolver().query(uri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION },
null,
null,
null);
if (c != null && c.moveToFirst()) {
int col = c.getColumnIndex( MediaStore.Images.ImageColumns.ORIENTATION );
angle = c.getInt(col);
c.close();
}
return angle;
}
You can also read any other value you find in MediaStore.Images.ImageColumns
, like latitude and longitude.
This currently doesn’t work with file:///
Uris but can be easily tweaked.