Python 获取照片拍摄经纬度及时间

732 阅读4分钟

今天看到掘金上老哥的绿帽文章,提取图片的拍摄时间和地点,作为py初学者自然要学习一下代码,并且改良一下弄成脚本想着分享给身边不会编程的朋友,以后捉奸让你的男女朋友现发一张照片给你也是极好的~

处理他人私密信息是违法的,仅供学习参考

代码

第一版

import exifread
import re
import json
import requests
import os
# 转换经纬度格式
def latitude_and_longitude_convert_to_decimal_system(*arg):
    """
    经纬度转为小数, param arg:
    :return: 十进制小数
    """
    return float(arg[0]) + ((float(arg[1]) + (float(arg[2].split('/')[0]) / float(arg[2].split('/')[-1]) / 60)) / 60)
# 读取照片的GPS经纬度信息
def find_GPS_image(pic_path):
    GPS = {}
    date = ''
    with open(pic_path, 'rb') as f:
        tags = exifread.process_file(f)
        for tag, value in tags.items():
            # 纬度
            if re.match('GPS GPSLatitudeRef', tag):
                GPS['GPSLatitudeRef'] = str(value)
            # 经度
            elif re.match('GPS GPSLongitudeRef', tag):
                GPS['GPSLongitudeRef'] = str(value)
            # 海拔
            elif re.match('GPS GPSAltitudeRef', tag):
                GPS['GPSAltitudeRef'] = str(value)
            elif re.match('GPS GPSLatitude', tag):
                try:
                    match_result = re.match(
                        '\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
                    GPS['GPSLatitude'] = int(match_result[0]), int(
                        match_result[1]), int(match_result[2])
                except:
                    deg, min, sec = [x.replace(' ', '')
                                     for x in str(value)[1:-1].split(',')]
                    GPS['GPSLatitude'] = latitude_and_longitude_convert_to_decimal_system(
                        deg, min, sec)
            elif re.match('GPS GPSLongitude', tag):
                try:
                    match_result = re.match(
                        '\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
                    GPS['GPSLongitude'] = int(match_result[0]), int(
                        match_result[1]), int(match_result[2])
                except:
                    deg, min, sec = [x.replace(' ', '')
                                     for x in str(value)[1:-1].split(',')]
                    GPS['GPSLongitude'] = latitude_and_longitude_convert_to_decimal_system(
                        deg, min, sec)
            elif re.match('GPS GPSAltitude', tag):
                GPS['GPSAltitude'] = str(value)
            elif re.match('.*Date.*', tag):
                date = str(value)
    return {'GPS_information': GPS, 'date_information': date}
# 通过baidu Map的API将GPS信息转换成地址。


def find_address_from_GPS(GPS):
    """
    使用Geocoding API把经纬度坐标转换为结构化地址。
    :param GPS:
    :return:
    """
    secret_key = 'zbLsuDDL4CS2U0M4KezOZZbGUY9iWtVf'
    if not GPS['GPS_information']:
        return '该照片无GPS信息'
    lat, lng = GPS['GPS_information']['GPSLatitude'], GPS['GPS_information']['GPSLongitude']
    baidu_map_api = "http://api.map.baidu.com/geocoder/v2/?ak={0}&callback=renderReverse&location={1},{2}s&output=json&pois=0".format(
        secret_key, lat, lng)
    response = requests.get(baidu_map_api)
    content = response.text.replace("renderReverse&&renderReverse(", "")[:-1]
    # print(content)
    baidu_map_address = json.loads(content)
    formatted_address = baidu_map_address["result"]["formatted_address"]
    province = baidu_map_address["result"]["addressComponent"]["province"]
    city = baidu_map_address["result"]["addressComponent"]["city"]
    district = baidu_map_address["result"]["addressComponent"]["district"]
    location = baidu_map_address["result"]["sematic_description"]
    return formatted_address, province, city, district, location
def main():
    try:
        img_path = input('')
        GPS_info = find_GPS_image(pic_path=img_path)
        address = find_address_from_GPS(GPS=GPS_info)
        print("拍摄时间:" + GPS_info.get("date_information"))
        print('照片拍摄地址:' + str(('').join(address)))
    except:
        print('是不是照片的路径错了,中文的:和英文:是不一样的哦~')
        main()
if __name__ == '__main__':
    print('请输入输入图片地址,')
    print('格式这种D:\照片\11.png')
    print('意思是D盘中的照片文件夹的11.png')
    main()

第二版

新增tkinter 模块,由原来的手动输入图片地址改为提示框选择,tkinter为内置模块,安装python时请配置,当初没有配置的可以更新pyhton进行配置

优化了操作交互,可多次解析图片

import exifread
import re
import json
import requests
import os
import tkinter as tk
from tkinter import filedialog
# 转换经纬度格式


def latitude_and_longitude_convert_to_decimal_system(*arg):
    """
    经纬度转为小数, param arg:
    :return: 十进制小数
    """
    return float(arg[0]) + ((float(arg[1]) + (float(arg[2].split('/')[0]) / float(arg[2].split('/')[-1]) / 60)) / 60)
# 读取照片的GPS经纬度信息


def find_GPS_image(pic_path):
    GPS = {}
    date = ''
    with open(pic_path, 'rb') as f:
        tags = exifread.process_file(f)
        for tag, value in tags.items():
            # 纬度
            if re.match('GPS GPSLatitudeRef', tag):
                GPS['GPSLatitudeRef'] = str(value)
            # 经度
            elif re.match('GPS GPSLongitudeRef', tag):
                GPS['GPSLongitudeRef'] = str(value)
            # 海拔
            elif re.match('GPS GPSAltitudeRef', tag):
                GPS['GPSAltitudeRef'] = str(value)
            elif re.match('GPS GPSLatitude', tag):
                try:
                    match_result = re.match(
                        '\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
                    GPS['GPSLatitude'] = int(match_result[0]), int(
                        match_result[1]), int(match_result[2])
                except:
                    deg, min, sec = [x.replace(' ', '')
                                     for x in str(value)[1:-1].split(',')]
                    GPS['GPSLatitude'] = latitude_and_longitude_convert_to_decimal_system(
                        deg, min, sec)
            elif re.match('GPS GPSLongitude', tag):
                try:
                    match_result = re.match(
                        '\[(\w*),(\w*),(\w.*)/(\w.*)\]', str(value)).groups()
                    GPS['GPSLongitude'] = int(match_result[0]), int(
                        match_result[1]), int(match_result[2])
                except:
                    deg, min, sec = [x.replace(' ', '')
                                     for x in str(value)[1:-1].split(',')]
                    GPS['GPSLongitude'] = latitude_and_longitude_convert_to_decimal_system(
                        deg, min, sec)
            elif re.match('GPS GPSAltitude', tag):
                GPS['GPSAltitude'] = str(value)
            elif re.match('.*Date.*', tag):
                date = str(value)
    return {'GPS_information': GPS, 'date_information': date}
# 通过baidu Map的API将GPS信息转换成地址。


def find_address_from_GPS(GPS):
    """
    使用Geocoding API把经纬度坐标转换为结构化地址。
    :param GPS:
    :return:
    """
    secret_key = 'zbLsuDDL4CS2U0M4KezOZZbGUY9iWtVf'
    if not GPS['GPS_information']:
        return '该照片无GPS信息'
    lat, lng = GPS['GPS_information']['GPSLatitude'], GPS['GPS_information']['GPSLongitude']
    baidu_map_api = "http://api.map.baidu.com/geocoder/v2/?ak={0}&callback=renderReverse&location={1},{2}s&output=json&pois=0".format(
        secret_key, lat, lng)
    response = requests.get(baidu_map_api)
    content = response.text.replace("renderReverse&&renderReverse(", "")[:-1]
    # print(content)
    baidu_map_address = json.loads(content)
    formatted_address = baidu_map_address["result"]["formatted_address"]
    province = baidu_map_address["result"]["addressComponent"]["province"]
    city = baidu_map_address["result"]["addressComponent"]["city"]
    district = baidu_map_address["result"]["addressComponent"]["district"]
    location = baidu_map_address["result"]["sematic_description"]
    return formatted_address, province, city, district, location
# 。


def output_path():
    img_path = filedialog.askopenfilename()
    GPS_info = find_GPS_image(pic_path=img_path)
    address = find_address_from_GPS(GPS=GPS_info)
    print("拍摄时间:" + GPS_info.get("date_information"))
    print('照片拍摄地址:' + str(('').join(address)))


def judge():
    print('输入 y 继续导入照片,n 终止程序')
    if_continue = input('')
    if(if_continue == 'y'):
        main()
    elif(if_continue == 'n'):
        exit()
    else:
        judge()


def main():
    try:
        output_path()
        judge()
    except:
        pass


if __name__ == '__main__':
    # 隐藏tk窗口
    root = tk.Tk()
    root.withdraw()
    main()

编译

为了分享给身边的朋友(仅供好玩),需要编译成脚本,作为python初学者,查阅了原来只需要 pip install pyinstaller先下载pyinstaller,然后运行pyinstaller -F photo.py

  • -F 表示生成单个可执行文件
  • -w 表示去掉控制台窗口,这在GUI界面时非常有用。不过如果是命令行程序的话那就把这个选项删除吧!
  • -p 表示你自己自定义需要加载的类路径,一般情况下用不到
  • -i 表示可执行文件的图标 photo.py是我脚本的名字,请确保终端是在脚本目录下进行的哦,会生成dist文件夹,里面就是我们需要的脚本

运行效果

image.png

提示

如果关闭手机拍照定位,则照片不会附带定位信息。右键照片属性,点击查看详情也能获得照片拍摄的经纬度