手動(dòng)修改圖片exif信息,如何用python代碼實(shí)現(xiàn)

小云
297
2023-08-19 15:13:22

要手動(dòng)修改圖片的EXIF信息,可以使用Python的PIL庫(kù)(Pillow)來(lái)實(shí)現(xiàn)。以下是一個(gè)示例代碼,演示如何使用PIL庫(kù)修改圖片的拍攝日期(DateTime)的EXIF信息:

from PIL import Image
from PIL.ExifTags import TAGS
def modify_exif(image_path, new_datetime):
# 打開圖片
image = Image.open(image_path)
# 獲取圖片的EXIF信息
exif_data = image._getexif()
# 將EXIF信息轉(zhuǎn)換為字典形式
exif_dict = {TAGS[key]: exif_data[key] for key in exif_data.keys() if key in TAGS and isinstance(exif_data[key], (str, int))}
# 修改拍攝日期的EXIF信息
exif_dict['DateTimeOriginal'] = new_datetime
exif_dict['DateTimeDigitized'] = new_datetime
# 將修改后的EXIF信息轉(zhuǎn)換回元組形式
new_exif_data = {TAGS[key]: exif_dict[TAGS[key]] for key in exif_dict.keys()}
new_exif_data = {key: new_exif_data[key] for key in new_exif_data.keys() if isinstance(new_exif_data[key], int)}
new_exif_data = {TAGS[key]: new_exif_data[key] for key in new_exif_data.keys() if key in TAGS}
# 創(chuàng)建一個(gè)新的圖片對(duì)象,將修改后的EXIF信息寫入其中
new_image = image.copy()
new_image.save("modified_image.jpg", exif=new_exif_data)
print("修改成功")
# 示例用法
image_path = "example.jpg"
new_datetime = "2022:01:01 12:00:00"
modify_exif(image_path, new_datetime)

在上面的示例中,modify_exif函數(shù)接受一個(gè)圖片路徑和一個(gè)新的拍攝日期作為參數(shù)。函數(shù)通過PIL庫(kù)打開圖片,并使用_getexif方法獲取圖片的EXIF信息。然后,將EXIF信息轉(zhuǎn)換為字典形式,修改拍攝日期的值,并將修改后的EXIF信息轉(zhuǎn)換回元組形式。最后,創(chuàng)建一個(gè)新的圖片對(duì)象,將修改后的EXIF信息寫入其中,并保存為一個(gè)新的圖片文件。

請(qǐng)注意,要使用PIL庫(kù),你需要通過pip install pillow命令安裝它。

0