How to use ExifInterface with a stream or URI

2019-02-21 17:45发布

问题:

I'm writing an app that can be sent a photo URI from the "Share via" menu in Android.

The kind of URI you get is content://media/external/images/media/556 however ExifInterface wants a standard file name. So how do I read the exif data (I just want orientation) of that file? Here's my (non-working) code:

Uri uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM);
ContentResolver cr = getContentResolver();
InputStream is = cr.openInputStream(uri);
Bitmap bm = BitmapFactory.decodeStream(is);

// This line doesn't work:
ExifInterface exif = new ExifInterface(uri.toString()); 
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

Any help (other than "you have to write your own ExifInterface class") is appreciated!

回答1:

I found the answer randomly in the Facebook Android SDK examples. I haven't tested it, but it looks like it should work. Here's the code:

public static int getOrientation(Context context, Uri photoUri) {
    /* it's on the external media. */
    Cursor cursor = context.getContentResolver().query(photoUri,
            new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);

    int result = -1;
    if (null != cursor) {
        if (cursor.moveToFirst()) {
            result = cursor.getInt(0);
        }
        cursor.close();
    }

    return result;
}


回答2:

You can get an ExifInterface using a filename string or InputStream, by doing importing the support ExifInterface in your build.gradle file:

compile 'com.android.support:exifinterface:26.1.0'

then:

private getExifInterfaceFromUri(Uri uri) throws IOException{
    FileInputStream fi = new FileInputStream(uri.getPath());

    return new ExifInterface(stream);
}

Remember that in Android there are multiple Uri types and you may need to use a Content Resolver and other approaches to get the real path from an Uri.