如何从InputStream而不是文件中获取Exif数据?

Wil*_*zel 8 android exif image file path

我问这个的原因是因为文件选择器的回调Intent返回了一个Uri.

通过Intent打开文件选择器:

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), CHOOSE_IMAGE_REQUEST);
Run Code Online (Sandbox Code Playgroud)

打回来:

@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CHOOSE_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {

        if (data == null) {
            // Error
            return;
        }

        Uri fileUri = data.getData();
        InputStream in = getContentResolver().openInputStream(fileUri);

        // How to determine image orientation through Exif data here?
    }
}
Run Code Online (Sandbox Code Playgroud)

一种方法是写InputStream一个实际的File,但这对我来说似乎是一个糟糕的解决方法.

noe*_*noe 13

在引入25.1.0支持库之后,现在可以通过一个从URI内容(content://或file://)读取exif数据InputStream.

示例:首先将此行添加到您的gradle文件中:

编译'com.android.support:exifinterface:25.1.0'

Uri uri; // the URI you've received from the other app
InputStream in;
try {
  in = getContentResolver().openInputStream(uri);
  ExifInterface exifInterface = new ExifInterface(in);
  // Now you can extract any Exif tag you want
  // Assuming the image is a JPEG or supported raw format
} catch (IOException e) {
  // Handle any errors
} finally {
  if (in != null) {
    try {
      in.close();
    } catch (IOException ignored) {}
  }
}
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息检查:介绍ExifInterface支持库,ExifInterface.