图片信息都保存在文件头部,以 Exif (Exchangeable image file format 可交换图像文件格式)格式保存,包含图片位置信息。在拍照时如果开启记录位置则可以获取到相应信息。获取代码如下
fun getPicExif(fileName: String): String {
val exif = ExifInterface()
try {
val inputStream: InputStream = assets.open(fileName)
exif.readExif(inputStream)
} catch (e: FileNotFoundException) {
Log.w(
TAG,
"Could not find file to read exif: $fileName",
e
)
return "";
} catch (e: IOException) {
Log.w(
TAG,
"Could not read exif from file: $fileName",
e
)
return "";
}
val latitudeTag = exif.getTag(ExifInterface.TAG_GPS_LATITUDE)
val longitudeTag = exif.getTag(ExifInterface.TAG_GPS_LONGITUDE)
var value = ""
if (latitudeTag != null && longitudeTag != null) {
val latitude = latitudeTag.getValueAsRationals()[0].toDouble()
val longitude = longitudeTag.getValueAsRationals()[0].toDouble()
value = "N " + latitude + " E" + longitude;
}
Log.i(TAG, "value " + value);
return value;
}
latitudeTag.getValueAsRationals() 获取的是其经纬度坐标,需要注意保存的位置信息可能是按照 118°22′22″ 度分秒的方式保存,那这个数组长度就是3,需要获取数组中所有数据,改进获取数据方式如下:
Rational[] rLati = latitudeTag.getValueAsRationals();
Rational[] rLongi = longitudeTag.getValueAsRationals();
double latitude;
double longitude;
if (rLati.length == 3) {
latitude = (rLati[2].toDouble() / 60 + rLati[1].toDouble()) / 60 + rLati[0].toDouble();
} else {
latitude = rLati[0].toDouble();
}
if (rLongi.length == 3) {
longitude = (rLongi[2].toDouble() / 60 + rLongi[1].toDouble()) / 60 + rLongi[0].toDouble();
} else {
longitude = rLongi[0].toDouble();
}