EXIF数据读写

swift

1个回答

写回答

13464105550

2025-06-16 09:25

+ 关注

Python
Python

EXIF数据读写

EXIF(Exchangeable Image File Format)是一种用于存储图像和音频文件附加信息的标准格式。这些附加信息包括拍摄设备的制造商和型号、拍摄日期和时间、曝光参数等。通过读取和写入EXIF数据,我们可以获取图像的详细信息,也可以向图像中添加自定义的附加信息。

读取EXIF数据

Python中,我们可以使用第三方库Pillow来读取图像的EXIF数据。以下是一个读取图像EXIF数据的示例代码:

Python

from PIL import Image

def read_exif_data(image_path):

try:

image = Image.open(image_path)

exif_data = image._getexif()

if exif_data is not None:

for tag, value in exif_data.items():

tag_name = Image.TAGS.get(tag)

print(f"{tag_name}: {value}")

else:

print("No EXIF data found.")

except Exception as e:

print(f"Error: {e}")

# 调用示例

read_exif_data("example.jpg")

上述代码中,我们首先使用Image.open()函数打开一张图像,然后通过_getexif()方法获取EXIF数据。如果EXIF数据存在,我们遍历EXIF数据中的每个标签和值,并将其打印出来。如果EXIF数据不存在,则打印出"No EXIF data found."。

写入EXIF数据

除了读取EXIF数据,我们还可以使用Pillow库来向图像中添加自定义的EXIF数据。以下是一个向图像中写入EXIF数据的示例代码:

Python

from PIL import Image

def write_exif_data(image_path, exif_data):

try:

image = Image.open(image_path)

image.save(image_path, exif=exif_data)

print("EXIF data written successfully.")

except Exception as e:

print(f"Error: {e}")

# 调用示例

exif_data = {

271: 'Custom Camera Model',

272: '2022:01:01 10:00:00',

# 其他自定义的EXIF标签和值

}

write_exif_data("example.jpg", exif_data)

上述代码中,我们首先使用Image.open()函数打开一张图像,然后使用save()方法将图像保存回原文件,并将自定义的EXIF数据作为参数传递给exif参数。如果写入EXIF数据成功,我们打印出"EXIF data written successfully."。

案例代码

下面是一个完整的示例代码,演示了如何读取和写入图像的EXIF数据:

Python

from PIL import Image

def read_exif_data(image_path):

try:

image = Image.open(image_path)

exif_data = image._getexif()

if exif_data is not None:

for tag, value in exif_data.items():

tag_name = Image.TAGS.get(tag)

print(f"{tag_name}: {value}")

else:

print("No EXIF data found.")

except Exception as e:

print(f"Error: {e}")

def write_exif_data(image_path, exif_data):

try:

image = Image.open(image_path)

image.save(image_path, exif=exif_data)

print("EXIF data written successfully.")

except Exception as e:

print(f"Error: {e}")

# 读取EXIF数据

read_exif_data("example.jpg")

# 写入EXIF数据

exif_data = {

271: 'Custom Camera Model',

272: '2022:01:01 10:00:00',

# 其他自定义的EXIF标签和值

}

write_exif_data("example.jpg", exif_data)

通过读取和写入EXIF数据,我们可以获取和修改图像的附加信息,这对于图像处理和管理非常有用。使用Python中的Pillow库,我们可以轻松地读取和写入图像的EXIF数据,使我们能够更好地了解图像的拍摄情况和相关信息。

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号