但对其他人来说,读取这些属性才是最具实用价值,这也是改进最大的方面。
首先,您可以读取 JPEG 和原始图片(具体地讲,DNG、CR2、NEF、NRW、ARW、RW2、ORF、PEF、SRW 和 RAF 文件)的 Exif 数据。这是在内部进行重大重构的成果,为确保所有环节真正发挥作用,我们移除了全部原生依赖项并构建了一个大范围测试套件。
对于通过 content:// URI 从其他应用接收图片(例如由目标 API 级别为 24 或更高级别的应用发送的图片)的应用,ExifInterface 现在可直接处理 InputStream;这样一来,您就可以方便地直接从收到的 content:// URI 提取 Exif 信息,而无需创建临时文件。
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) {}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Uriuri;// the URI you've received from the other app
InputStreamin;
try{
in=getContentResolver().openInputStream(uri);
ExifInterfaceexifInterface=newExifInterface(in);
// Now you can extract any Exif tag you want
// Assuming the image is a JPEG or supported raw format
}catch(IOExceptione){
// Handle any errors
}finally{
if(in!=null){
try{
in.close();
}catch(IOExceptionignored){}
}
}
注:ExifInterface 无法处理远程 InputStream,例如从 HttpURLConnection 返回的输入流。强烈建议只使用它来处理 content:// 或 file:// URI。
对于大多数属性,您只需视情况使用 getAttributeInt()、getAttributeDouble() 或 getAttribute()(适用于字符串)。
就显示图片而言,其中一个最重要的属性是图片方向,存储该信息的 TAG_ORIENTATION 恰如其名,用于返回其中一个 ORIENTATION_ 常量。可通过后处理将该值转换为旋转角度。
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
introtation=0;
intorientation=exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch(orientation){
caseExifInterface.ORIENTATION_ROTATE_90:
rotation=90;
break;
caseExifInterface.ORIENTATION_ROTATE_180:
rotation=180;
break;
caseExifInterface.ORIENTATION_ROTATE_270:
rotation=270;
break;
}
可通过一些辅助工具方法从特定 Exif 标记提取值。对于位置数据,getLatLong() 方法提供使用浮点值表示的经度和纬度,getAltitude() 提供使用米表示的海拔高度。一些图片还嵌入了小型缩略图。可通过 hasThumbnail() 检查其是否存在,然后通过 getThumbnail()提取缩略图的 byte[] 表示形式 – 后者最适合用来向 BitmapFactory.decodeByteArray() 传递数据。