
ExifInterface 支持库简介
来源:Android Developers Blog
作者:Google 开发技术推广工程师 Ian Lake
基本功能仍然相同:对嵌入图片文件的 Exif 标记进行读写的功能:现已包含 140 个不同的属性(其中近 100 个是 Android 7.1/该支持库新增的!),包括有关相机本身、相机设置、屏幕方向以及 GPS 坐标的信息。
首先,您可以读取 JPEG 和原始图片(具体地讲,DNG、CR2、NEF、NRW、ARW、RW2、ORF、PEF、SRW 和 RAF 文件)的 Exif 数据。这是在内部进行重大重构的成果,为确保所有环节真正发挥作用,我们移除了全部原生依赖项并构建了一个大范围测试套件。
对于通过 content:// URI 从其他应用接收图片(例如由目标 API 级别为 24 或更高级别的应用发送的图片)的应用,ExifInterface 现在可直接处理 InputStream;这样一来,您就可以方便地直接从收到的 content:// URI 提取 Exif 信息,而无需创建临时文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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) {} } } |
注:ExifInterface 无法处理远程 InputStream,例如从 HttpURLConnection 返回的输入流。强烈建议只使用它来处理 content:// 或 file:// URI。
对于大多数属性,您只需视情况使用 getAttributeInt()、getAttributeDouble() 或 getAttribute()(适用于字符串)。
就显示图片而言,其中一个最重要的属性是图片方向,存储该信息的 TAG_ORIENTATION 恰如其名,用于返回其中一个 ORIENTATION_ 常量。可通过后处理将该值转换为旋转角度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
int rotation = 0; int orientation = exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotation = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotation = 270; break; } |
可通过一些辅助工具方法从特定 Exif 标记提取值。对于位置数据,getLatLong() 方法提供使用浮点值表示的经度和纬度,getAltitude() 提供使用米表示的海拔高度。一些图片还嵌入了小型缩略图。可通过 hasThumbnail() 检查其是否存在,然后通过 getThumbnail()提取缩略图的 byte[] 表示形式 – 后者最适合用来向 BitmapFactory.decodeByteArray() 传递数据。
将 ExifInterface 支持库添加到项目中时附带以下依赖项:
1 2 3 4 |
compile "com.android.support:exifinterface:25.1.0" |
但如果您恰好需要某个 Exif 属性来防止应用内的图片旋转方向出错,那么 ExifInterface 支持库正合乎您 #BuildBetterApps 的需要。