为图片设置经纬度信息

一、java实现
小编看了很多技术博客,但是测试要么下载的jar包中的api和博客对不上,要么就是不对,总之没实现
Java 读取图片信息
java 写入 exif 信息
使用Java读取和修改图片的Exif信息
java获取图片的GPS信息
https://drewnoakes.com/code/exif/
https://github.com/drewnoakes/metadata-extractor/
java 修改图片exif信息
JAVA 使用metadata-extractor添加水印
java 修改照片exif信息
ava图片识别文字软件 java识别图片文字 原理
java 修改图片exif信息
如何用一张照片进行GPS定位
https://www.jb51.net/program/319520ppk.htm
https://blog.csdn.net/qq_40985985/article/details/118605888
https://blog.51cto.com/u_16213361/10406427
https://blog.csdn.net/m0_51363655/article/details/125554155
https://blog.csdn.net/weixin_42350212/article/details/118467097
二、python实现
引用给家里的老照片添加时间、地点信息,方便查找回忆

from PIL import Image, ImageTk
from piexif import load, dump, ImageIFD,GPSIFD
import tkinter as tk
from tkinter import filedialog, messagebox
import pyperclip

def open_file():
    print("打开文件 start")
    file_path = filedialog.askopenfilename(title='选择图片文件')
    # file_path = 'C:/Users/hahaha/Pictures/IMG_1089.JPG'
    print(file_path)
    img = Image.open(file_path)
    img = img.resize((400, 300))
    img = ImageTk.PhotoImage(img)
    lable_img_display.config(image=img)
    lable_img_display.image = img

    if file_path:
        print("打开文件:", file_path)
        # 打开图片
        image = Image.open(file_path)
        img_name_old_label.config(text=file_path)

        # 读取图片的原始exif信息'
        try:
            exif_dic = load(image.info["exif"])
            image_time = exif_dic["0th"][ImageIFD.DateTime]
            print(image_time)
            img_time_old_label.config(text=image_time)
            if exif_dic["GPS"]:
                longtitude = exif_dic['GPS'][GPSIFD.GPSLongitude] # 经度
                print(format_data(longtitude))
                img_longtitude_old_label.config(text=format_data(longtitude))
                latitude = exif_dic["GPS"][GPSIFD.GPSLatitude]
                print(format_data(latitude))
                img_latitude_old_label.config(text=format_data(latitude)) # 纬度
                print(longtitude)
                print(latitude)
                print(format_data(format_data(longtitude)))
            else:
                print("无GPS信息")
                img_longtitude_old_label.config(text="none")
                img_latitude_old_label.config(text="none")
                pass
        except:
            img_time_old_label.config(text="none")
            img_longtitude_old_label.config(text="none")
            img_latitude_old_label.config(text="none")


def format_data(latlong):
    print(type(latlong))
    if type(latlong) == float or type(latlong) == str or type(latlong) == int:
        latlong = float(latlong)
        degree = int(latlong)
        res_degree = latlong - degree
        minute = int(res_degree * 60)
        res_minute = res_degree * 60 - minute
        seconds = round(res_minute * 60, 3)

        _data = ((degree, 1), (minute, 1), (int(seconds * 100), 100))
        return _data
    elif type(latlong) == tuple:
        _date = latlong[0][0]+latlong[1][0]/60+latlong[2][0]/60/6000
        return _date


def save_file():
    file_path = filedialog.asksaveasfilename()
    if file_path:
        print("保存文件:", file_path)

def modify_exif():

    print('修改图片的exif信息')
    # 打开图片
    image_path = img_name_old_label.cget("text")
    image = Image.open(image_path)

    # 读取图片的原始exif信息
    try:
        exif_data = load(image.info["exif"])
    except:
        exif_data = {}

    if '0th' not in exif_data:  # 判断是否存在基础信息 并创建基础信息
        exif_data['0th'] = {}
    if len(exif_data['0th']) == 0:
        exif_data['0th'] = {
            271: b'QRJ', #制造商
            272: b'scanner',#型号
            # 274: 1, # 图像方向
            # 282: (72, 1), #ImageWidth 方向上每个 ResolutionUnit 的像素数
            # 283: (72, 1), #ImageLength方向上每个 ResolutionUnit 的像素数
            # 296: 2, #XResolution 和 YResolution 的测量单位。
            305: b'IMG_EDITv1', #用于创建映像的软件包的名称和版本号。
            306: b'2000:00:00 00:00:00', # 创建时间
            # 531: 1,# 指定子采样色度分量相对于亮度样本的位置。
            # 34665: 208,
            # 34853: 1786
        }
        exif_data['0th'][ImageIFD.DateTime] = img_time_new_text.get()  # 创建基础exif空字典

    if 'GPS' not in exif_data: # 判断是否存在基础GPS信息 并创建GPS基础信息
        exif_data['GPS'] = {} # 创建gps空字典
    if len(exif_data['GPS']) == 0:
        exif_data['GPS'] = {
            1: b'N', # 南北纬
            2: ((40, 1), (6, 1), (2386, 100)), # 纬度
            3: b'E', #东西经
            4: ((116, 1), (32, 1), (5287, 100)), # 经度
            # 5: 0, #表示作为参考高度的高度
            # 6: (13973, 415), #根据 GPSAltitudeRef 中的参考值指示高度
            # 7: ((4, 1), (5, 1), (4760, 100)), #表示时间为 UTC(协调世界时)。
            # 12: b'K', #表示用于表示 GPS 接收器移动速度的单位。
            # 13: (0, 1), #表示GPS接收器移动的速度
            # 16: b'T', #表示在捕获图像时给出图像方向的参考。
            # 17: (10159, 338), #表示图像拍摄时的方向。
            # 23: b'T', #表示用于给目标点方位的参考。
            # 24: (10159, 338), #表示到目的地的方位。
            # 29: b'2000:00:00', #一个字符串,记录相对于 UTC(协调世界时)的日期和时间信息。
            # 31: (65, 1) #指示是否对 GPS 接收器应用差分校正。
        }
        # if GPSIFD.GPSLongitude not in exif_data['GPS']:
#     exif_data['GPS'][GPSIFD.GPSLongitude] = []  # 创建gps空列表
        if img_longtitude_new_text.get() == '':
            messagebox.showinfo("提示", "请输入经度")
            return

        exif_data['GPS'][GPSIFD.GPSLongitude] = format_data(img_longtitude_new_text.get()) # 更新经度
# if GPSIFD.GPSLatitude not in exif_data['GPS']:
#     exif_data['GPS'][GPSIFD.GPSLatitude] = []
        if img_latitude_new_text.get() == '':
            messagebox.showinfo("提示", "请输入纬度")
            return
        exif_data['GPS'][GPSIFD.GPSLatitude] = format_data(img_latitude_new_text.get()) # 更新纬度




    ########################EXIF信息################################

    if 'Exif' not in exif_data:  # 判断是否存在Exif信息 并创建Exif信息
        exif_data['Exif'] = {}
    if len(exif_data['Exif']) == 0:
        exif_data['Exif'] = {
            # 33434: (1, 400),
            # 33437: (22, 10),
            # 34850: 3,
            # 34855: 100,
            # 34864: 2,
            # 34866: 100,
            # 36864: b'0230',
            36867: b'2022:10:30 17:01:01',
            # 36868: b'2022:10:30 17:02:02',
            # 37121: b'\x01\x02\x03\x00',
            # 37377: (565248, 65536),
            # 37378: (155648, 65536),
            # 37380: (0, 1),
            # 37383: 5,
            # 37385: 16,
            # 37386: (50, 1),
            # 42037: b'0000205042\x00'
        }
        exif_data['Exif'][36867] = img_time_new_text.get()  # 创建Exif时间信息

        #############Interop信息#######################################

        # if 'Interop' not in exif_data:
        #     exif_data['Interop'] = {}
        # if len(exif_data['Interop']) == 0:
        #     exif_data['Interop'] = {1: b'R98'}
        #


        #################1st##############
        # if '1st' not in exif_data:
        #     exif_data['1st'] = {}
        # if len(exif_data['1st']) == 0:
        #     exif_data['1st'] = {
        #         259: 6,
        #         282: (72, 1),
        #         283: (72, 1),
        #         296: 2,
        #         513: 8916,
        #         514: 14640
        #     }
    # 修改原始exif信息
    # exif_data.update(new_exif_dict)
    exif_bytes = dump(exif_data)

    # 设置新的exif信息
    image.save(image_path, exif=exif_bytes)






def paste_location():
    # TODO: 从剪贴板中粘贴经纬度
    gps_info=pyperclip.paste()
    print(gps_info)
    if ',' in gps_info:
        gps_info = gps_info.split(',')
        img_longtitude_new_text.insert(tk.END, gps_info[0])
        img_latitude_new_text.insert(tk.END, gps_info[1])

    pass

if __name__ == '__main__':
    # TODO: 实现GUI或者命令行接口,让用户选择操作
    root = tk.Tk()
    root.title("文件对话框")
    root.geometry("600x500")


    img_info_frame = tk.Frame(root)
    img_info_frame.pack(pady=20)
    img_name_label = tk.Label(img_info_frame, text="图片名称")
    img_name_label.grid(row=0, column=0)
    img_name_old_label = tk.Label(img_info_frame, text="原图片")
    img_name_old_label.grid(row=0, column=1)
    img_time_label = tk.Label(img_info_frame, text="图片时间")
    img_time_label.grid(row=1, column=0)
    img_time_old_label = tk.Label(img_info_frame, text="原图片时间")
    img_time_old_label.grid(row=1, column=1)
    img_time_new_text = tk.Entry(img_info_frame, width=20)
    img_time_new_text.grid(row=1, column=2)
    img_time_new_text.insert(tk.END, "2018:02:02 21:44:35")
    # img_time_new_text.config(state=tk.DISABLED)

    img_longitude_label = tk.Label(img_info_frame, text="经度")
    img_longitude_label.grid(row=2, column=0)
    img_longtitude_old_label = tk.Label(img_info_frame, text="原经度")
    img_longtitude_old_label.grid(row=2, column=1)
    img_longtitude_new_text = tk.Entry(img_info_frame, width=20)
    img_longtitude_new_text.grid(row=2, column=2)


    img_latitude_label = tk.Label(img_info_frame, text="纬度")
    img_latitude_label.grid(row=3, column=0)
    img_latitude_old_label = tk.Label(img_info_frame, text="原纬度")
    img_latitude_old_label.grid(row=3, column=1)
    img_latitude_new_text = tk.Entry(img_info_frame, width=20)
    img_latitude_new_text.grid(row=3, column=2)

    button_frame = tk.Frame(root,width=600,height=50)
    button_frame.pack()
    open_button = tk.Button(button_frame, text="打开单独文件", command=open_file)
    open_button.grid(row=4, column=2)

    save_button = tk.Button(button_frame, text="保存文件", command=save_file)
    save_button.grid(row=4, column=3)

    modify_button = tk.Button(button_frame, text="修改exif", command=modify_exif)
    modify_button.grid(row=4, column=4)

    paste_button = tk.Button(button_frame, text="粘贴经纬度", command=paste_location)
    paste_button.grid(row=4, column=5)

    website_text = tk.Text(root, width=54, height=1)
    website_text.pack()
    website_text.insert(tk.END, "https://api.map.baidu.com/lbsapi/getpoint/index.html")
    lable_img_display = tk.Label(root,width=400,height=300)
    lable_img_display.pack()
    #webview2 创建坐标浏览页面
    # web_view = tk.
    root.mainloop()
    pass

引用单反相机照片用python 脚本添加gps位置信息
三方依赖库

pip install piexif
pip install pywin32
pip install Pillow
pip install pyinstaller
# ecoding:utf-8
import os
from PIL import Image
import piexif
import win32con
import win32ui
import ctypes
 
"""
安装第三方包
pip install piexif
pip install pywin32
pip install Pillow
pip install pyinstaller
打包命令:pyinstaller -F -i .\gps.ico .\gps.py
"""
 
# DIP缩放设置
awareness = ctypes.c_int()
errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(0, ctypes.byref(awareness))
errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)
success = ctypes.windll.user32.SetProcessDPIAware()
 
 
def main():
    image_path = browse(True)[1]
    gps_str = input('请输入经纬度:')
    arr = gps_str.split(',')
    lng = float(arr[1])
    lat = float(arr[0])
 
    # 将经纬度与相对航高转为exif可用的经纬度与行高
    # exif需要的航高输入为(20000,2)格式,表示高度为20000/100米
    # exif需要的经度与维度为((12, 1), (20,1), (41000, 1000))格式表示12度20分41秒
    lng_exif = format_latlng(lng)
    lat_exif = format_latlng(lat)
    _dict = {"lng": lng_exif, "lat": lat_exif, "lng_ref": 'E', "lat_ref": 'N'}
    print("写入文件:", image_path)
    # 判断图片是否有exif
    read_check_exif(image_path)
    # 修改图片的exif
    read_modify_exif(image_path, _dict)
 
 
def browse(mode: bool,
           default_name: str = "",
           title: str = "选择您的文件",
           file_type: str = "图片文件(*.jpg)|*.jpg|",
           path: str = "desktop"):
    """弹出窗口返回保存或者选择的路径
    :param mode: False"为 "保存/另存为", "True"为 "打开"
    :param default_name:默认输入文件名
    :param title:窗口提示
    :param file_type:可选的文件类型,所有文件(*.*)|*.*|图片文件(*.jpg)|*.jpg|
    :param path:
    :return:[存储类型、文件路径、文件类型]
    """
    api_flag = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_FILEMUSTEXIST
    dlg = win32ui.CreateFileDialog(mode, None, default_name, api_flag, file_type)
    dlg.SetOFNTitle(title)
    dlg.SetOFNInitialDir(os.path.abspath(path))
    dlg.DoModal()
    filename = dlg.GetPathName()
    fileExt = dlg.GetFileExt()
    if os.path.exists(filename):
        if_pass = True
    elif not mode:
        if os.path.split(filename)[0] == '':
            if_pass = False
        else:
            if_pass = True
    else:
        if_pass = False
    return [if_pass, filename, fileExt]
 
 
def format_latlng(latlng):
    """经纬度十进制转为分秒"""
    degree = int(latlng)
    res_degree = latlng - degree
    minute = int(res_degree * 60)
    res_minute = res_degree * 60 - minute
    seconds = round(res_minute * 60.0, 3)
 
    return ((degree, 1), (minute, 1), (int(seconds * 1000), 1000))
 
 
def read_check_exif(image_path):
    """
    判断图片是否有'exif'信息,没有就写入初始'exif'信息
    :param image_path:图片路径
    :return:无
    """
    img = Image.open(image_path)  # 读图
    try:
        exif_dict = piexif.load(img.info['exif'])  # 提取exif信息
    except KeyError:
        # 处理exif不存在的情况
        # 创建一个初始的EXIF字典
        exif_dict = {"0th": {}, "Exif": {}, "GPS": {}, "Interop": {}, "1st": {}, "thumbnail": None}
        # 将EXIF字典添加到图像的元数据中
        exif_bytes = piexif.dump(exif_dict)
        img.save(image_path, exif=exif_bytes)
 
 
def read_modify_exif(image_path, _dict):
    """ 读取并且修改exif文件"""
    img = Image.open(image_path)  # 读图
    exif_dict = piexif.load(img.info['exif'])  # 提取exif信息
 
    exif_dict['GPS'][piexif.GPSIFD.GPSLongitude] = _dict['lng']  # 修改经度
    exif_dict['GPS'][piexif.GPSIFD.GPSLatitude] = _dict['lat']  # 修改纬度
    exif_dict['GPS'][piexif.GPSIFD.GPSLongitudeRef] = _dict['lng_ref']  # odm需要读取,一般为’W'
    exif_dict['GPS'][piexif.GPSIFD.GPSLatitudeRef] = _dict['lat_ref']  # 一般为‘N'
 
    exif_bytes = piexif.dump(exif_dict)
    piexif.insert(exif_bytes, image_path)
 
 
if __name__ == "__main__":
    main()

可以用这个网站来看看位置信息
本工具可查看图片Exif信息、图片定位信息、图片GPS信息、图片经纬度信息
https://web.gpstool.com/index
拾取坐标
https://api.map.baidu.com/lbsapi/getpoint/index.html

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值