【问题标题】:How to use ExifInterface with a stream or URI如何将 ExifInterface 与流或 URI 一起使用
【发布时间】:2011-12-18 19:39:52
【问题描述】:

我正在编写一个可以从 Android 中的“分享方式”菜单发送照片 URI 的应用。

您获得的 URI 类型是 content://media/external/images/media/556,但 ExifInterface 需要标准文件名。那么如何读取该文件的 exif 数据(我只想要方向)?这是我的(非工作)代码:

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);

感谢任何帮助(除了“您必须编写自己的 ExifInterface 类”)!

【问题讨论】:

  • 你试过新的 ExifInterface(uri.getPath());此外,您也许可以查询内容 uri 的方向。

标签: android stream orientation uri exif


【解决方案1】:

我在 Facebook Android SDK 示例中随机找到了答案。我还没有测试它,但它看起来应该可以工作。代码如下:

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;
}

【讨论】:

  • 你好@timmmm,我厌倦了这段代码,用于使用 photouri 查找图像的方向。但是游标抛出空指针异常可能是它没有得到 photouri。你能提出任何解决方案吗?
  • @timmmm 在上面的代码中你忘记关闭光标 - 这是内存泄漏
  • @Gregory Facebook 忘记了!感谢您修复代码。顺便说一句,这就是垃圾收集垃圾的原因——你不能使用 RAII。
  • 请注意,这会返回以度为单位的文字方向,而不是像 ExifInterface 那样表示值的枚举。
  • @JustinMeiners 我正在使用 ExifInterface 和 StrictMode 正在选择一个 detectLeakedClosableObject 并杀死我的应用程序(penaltyDeath)
【解决方案2】:

您可以通过在 build.gradle 文件中导入支持 ExifInterface 来使用文件名字符串或 InputStream 获取 ExifInterface:

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

然后:

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

    return new ExifInterface(stream);
}

请记住,在 Android 中有多种 Uri 类型,您可能需要使用 Content Resolver 和其他方法从 Uri 获取真实路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    相关资源
    最近更新 更多