View 体系
View 体系 · androidx.core
ExifInterface:读取图片元数据Core 1.20.0-alpha01
读取 EXIF 标签、GPS 坐标与拍摄时间,以及写入后保存。
最后更新 2026-08-01
复制即用
import androidx.exifinterface.media.ExifInterface;
// 从文件/输入流读取
ExifInterface exif = new ExifInterface(file);
// 读取常用标签
String datetime = exif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL);
String make = exif.getAttribute(ExifInterface.TAG_MAKE);
String model = exif.getAttribute(ExifInterface.TAG_MODEL);
// 读取 GPS(返回 [纬度, 经度] 或 null)
double[] latLong = exif.getLatLong();
if (latLong != null) {
double latitude = latLong[0];
double longitude = latLong[1];
}写入并保存:
exif.setAttribute(ExifInterface.TAG_ARTIST, "me");
exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_ROTATE_90));
exif.saveAttributes();方向校正(旋转)
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
val matrix = Matrix().apply {
when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> postRotate(90f)
ExifInterface.ORIENTATION_ROTATE_180 -> postRotate(180f)
ExifInterface.ORIENTATION_ROTATE_270 -> postRotate(270f)
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> postScale(-1f, 1f)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> postScale(1f, -1f)
}
}
val rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)手机拍照的 JPEG 可能含方向标签,直接显示会横躺——读取 TAG_ORIENTATION 校正。
常见陷阱
- 先读 EXIF 再压缩:压缩/重编码会丢 EXIF。
- getLatLong 为空:无 GPS 标签时返回 null,要判空。
- saveAttributes 只读误调:会改写文件。
- orientation 默认值:
getAttributeInt要传默认值ORIENTATION_NORMAL。 - 流读取不关闭:InputStream 构造的 exif 用完要关流。
要点
- 构造方式:
File、String路径、FileDescriptor、InputStream。 - 常用标签:
TAG_DATETIME_ORIGINAL、TAG_MAKE/MODEL、TAG_ORIENTATION、TAG_GPS_LATITUDE/LONGITUDE。 getLatLong()直接返回[纬度, 经度](GPS 坐标已换算成小数)。saveAttributes()会把修改写回文件;只读场景不要调用。- 图片被压缩/重编码后 EXIF 可能丢失,需要先读再处理。
- 方向标签要校正,否则照片横躺。