概述
最近有个需求用户上传照片,并获取到照片拍摄时候的位置。网上搜索了相关资料,找到了Exif.js。本文就分享一下我的实验结果和实现。
分析
实现这样的一个需求有两种方式:
- 强制用户拍照,拍完照片后获取当前的位置作为拍摄照片时候的位置;
- 从相册选择照片,再获取照片的位置信息。
结论
快速的用uni-app搭了一个工程,试了下,结论是:
- 在安卓手机中拍摄的照片可以获取到,可以支持选择和拍摄两种方式;
- 在苹果手机中获取不到,只能拍摄。
实现
测试代码很简单,添加了一个按钮,点击按钮的时候选择照片,再将所有的信息打印输出。
<template>
<view class="content">
<button @click="chooseImage">chooseImage</button>
<img style="width: 100%;" :src="imageUrl" id="image"></img>
</view>
</template>
<script>
export default {
data() {
return {
imageUrl: ''
}
},
methods: {
chooseImage() {
const that = this
uni.chooseImage({
count: 1, //最多可以选择的图片张数,默认9
sizeType: ['original'], //original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'],
//album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
success: (res) => { //成功返回的函数
that.imageUrl = res.tempFilePaths[0]
console.log('图片路径为:', res.tempFilePaths[0]) //选着的图片
const img1 = new Image()
img1.src = res.tempFilePaths[0]
img1.onload = () => {
EXIF.getData(img1, function() {
const allMetaData = EXIF.getAllTags(this);
console.log(allMetaData)
});
}
},
fail: (err) => { //图片接口调用失败的回调函数
console.log('chooseImage fail', err)
}
})
}
}
}
</script>
安卓手机中getAllTags
返回的数据如下:
{
"undefined": "Redmi Note 12 Pro",
"ImageHeight": 2448,
"Make": "Xiaomi",
"Orientation": 1,
"DateTime": "2025:08:02 12:29:54",
"GPSInfoIFDPointer": 4677,
"YResolution": 72,
"XResolution": 72,
"ImageWidth": 3264,
"Model": "22101316C",
"Software": "MediaTek Camera Application",
"ImageDescription": "",
"YCbCrPositioning": 2,
"ExifIFDPointer": 501,
"ResolutionUnit": 2,
"ExifVersion": "",
"ExposureBias": 0,
"ExposureProgram": "Not defined",
"ColorSpace": 1,
"MaxApertureValue": 2,
"PixelYDimension": 2448,
"BrightnessValue": 7,
"DateTimeOriginal": "2025:08:02 12:29:54",
"FlashpixVersion": "0100",
"SubsecTimeOriginal": "850",
"WhiteBalance": "Auto white balance",
"InteroperabilityIFDPointer": 4934,
"ExposureMode": 0,
"ExposureTime": 0.019996,
"Flash": "Flash did not fire, compulsory flash mode",
"SubsecTime": "850",
"FNumber": 2.2,
"PixelXDimension": 3264,
"ISOSpeedRatings": 329,
"ComponentsConfiguration": "YCbCr",
"FocalLengthIn35mmFilm": 16,
"SubsecTimeDigitized": "850",
"DigitalZoomRation": 1,
"DateTimeDigitized": "2025:08:02 12:29:54",
"ShutterSpeedValue": 2.321,
"MeteringMode": "CenterWeightedAverage",
"FocalLength": 1.66,
"SceneCaptureType": "Standard",
"LightSource": "Other",
"GPSLatitude": [
22,
33,
4.9248
],
"GPSAltitude": 0,
"GPSLatitudeRef": "N",
"GPSSpeed": 0,
"GPSAltitudeRef": 0,
"GPSProcessingMethod": "network",
"GPSSpeedRef": "K",
"GPSVersionID": "2.2.0.0",
"GPSLongitudeRef": "E",
"GPSTimeStamp": [
4,
29,
54
],
"GPSLongitude": [
113,
52,
38.352
],
"GPSDateStamp": "2025:08:02",
"thumbnail": {
"YResolution": 72,
"Orientation": 1,
"Compression": 6,
"JpegIFOffset": 5155,
"JpegIFByteCount": 27648,
"XResolution": 72,
"undefined": "2025:08:02 12:29:54",
"YCbCrPositioning": 2,
"ResolutionUnit": 2,
"blob": {
}
}
}
数据中GPSLatitude
和GPSLongitude
即为返回的经纬度,格式为度、分、秒
,可根据需要进行转换。