Python代码

import exifread
import json
import requests
import os
 
## 高德API的key
gaodeapi_key = "348570adbb9aa5142104df44e11a82fc"
 
## 图片文件夹路径
folder_path = r'C:\Users\ChiGua\Desktop\1'
 
## 输出Markdown文件的文件夹路径
output_folder_path = r'C:\Users\ChiGua\Desktop\2'
 
## 高德API的网址
gaodeapi_sitehead = "https://restapi.amap.com/v3/assistant/coordinate/convert?locations="
 
## 高德逆地理编码API的URL
REVERSE_GEOCODING_URL = "https://restapi.amap.com/v3/geocode/regeo"
 
## 构建Markdown内容的函数
def build_markdown_content(image, tags, address, lat, lng, locations):
    markdown_content = "---\n"
    markdown_content += "mapmarker: default\n"
    markdown_content += "date: {}\n".format(tags.get('EXIF DateTimeOriginal', 'Unknown'))
    markdown_content += "device: {} {}\n".format(tags.get('Image Make', 'Unknown'), tags.get('Image Model', 'Unknown'))
    markdown_content += "place: {}\n".format(address)
    markdown_content += "gps: [{},{}]\n".format(lat, lng)
    markdown_content += "locations: [{}]\n".format(locations)
    markdown_content += "---\n"
    
    return markdown_content
 
## 获取经纬度的函数
def getLatOrLng(refKey, tudeKey, tags):
    if refKey not in tags:
        return None
    ref = tags[refKey].printable
    LatOrLng = tags[tudeKey].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
    LatOrLng = float(LatOrLng[0]) + float(LatOrLng[1]) / 60 + float(LatOrLng[2]) / float(LatOrLng[3]) / 3600
    if refKey == 'GPS GPSLatitudeRef' and tags[refKey].printable != "N":
        LatOrLng = -LatOrLng
    if refKey == 'GPS GPSLongitudeRef' and tags[refKey].printable != "E":
        LatOrLng = -LatOrLng
        
    return LatOrLng
 
## 发送请求并获取响应的函数
def send_request(url, params):
    response = requests.get(url, params=params)
    return response.json() if response.status_code == 200 else None
 
## 主函数
def main():
    os.makedirs(output_folder_path, exist_ok=True)
    for image in os.listdir(folder_path):
        if image.lower().endswith(('.png', '.jpg', '.jpeg')):
            with open(os.path.join(folder_path, image), 'rb') as f:
                tags = exifread.process_file(f)
                lat = getLatOrLng('GPS GPSLatitudeRef', 'GPS GPSLatitude', tags)
                lng = getLatOrLng('GPS GPSLongitudeRef', 'GPS GPSLongitude', tags)
                if lat is not None and lng is not None:
                    # 转换坐标
                    gaodeapi_site = gaodeapi_sitehead + str(lng) + ',' + str(lat) + '&coordsys=gps&output=json&key=' + gaodeapi_key
                    response_data = send_request(gaodeapi_site, {})
                    if response_data and response_data['status'] == '1':
                        # 使用转换后的坐标进行逆地理编码
                        gn = response_data['locations']
                        locations = response_data['locations'].split(',')[1] + ',' + response_data['locations'].split(',')[0]
                        params = {
                            'key': gaodeapi_key,
                            'location': gn,
                            'output': 'JSON',
                            'extensions': 'all'
                        }
                        address_response = send_request(REVERSE_GEOCODING_URL, params)
                        if address_response and address_response['status'] == '1':
                            address = address_response['regeocode']['formatted_address']
                            markdown_content = build_markdown_content(image, tags, address, lat, lng, locations)
                            md_filename = os.path.splitext(image)[0] + '.md'
                            md_file_path = os.path.join(output_folder_path, md_filename)
                            with open(md_file_path, 'w', encoding='utf-8') as md_file:
                                md_file.write(markdown_content)
                            print(f"Markdown file created for {image} with address {address}")
                        else:
                            print(f"Error getting address for {image}: {address_response['info'] if address_response else 'No response received'}")
                else:
                    print(f"No GPS coordinates found in {image}")
    print("All files processed.")
 
if __name__ == "__main__":
    main()

主要功能和解释

这段Python代码是一个脚本,它的作用是处理一个文件夹中的图片文件,提取它们的EXIF信息(包括拍摄时间、设备信息等),获取图片的GPS坐标,然后使用高德地图API将这些坐标转换为具体的地址信息,并生成相应的Markdown格式的文件。这些Markdown文件包含了图片的相关信息和地理位置,可以用于创建地图标记或者日志记录。

代码的主要步骤如下:

  1. 设置高德API的key和图片文件夹路径。
  2. 定义构建Markdown内容的函数build_markdown_content
  3. 定义获取经纬度的函数getLatOrLng
  4. 定义发送请求并获取响应的函数send_request
  5. main函数中,遍历指定文件夹中的图片文件。
  6. 对于每个图片文件,读取其EXIF信息,提取GPS坐标。
  7. 如果找到了GPS坐标,使用高德API进行坐标转换和逆地理编码,获取地址信息。
  8. 使用获取的信息构建Markdown内容。
  9. 将Markdown内容写入到新的Markdown文件中。
  10. 如果处理过程中出现错误,打印错误信息。