Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ExifInterface with a stream or URI

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!

like image 658
Timmmm Avatar asked Dec 18 '11 19:12

Timmmm


2 Answers

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;
}
like image 88
3 revs, 3 users 76% Avatar answered Nov 15 '22 21:11

3 revs, 3 users 76%


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.

like image 43
Vitor Hugo Schwaab Avatar answered Nov 15 '22 19:11

Vitor Hugo Schwaab