Created
September 11, 2022 12:14
-
-
Save Moraxyc/bec76bc95d0d7c4db8bd769df90c85c5 to your computer and use it in GitHub Desktop.
通过文件名为照片添加时间元数据的脚本(@Wendell 2021.04原创)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import piexif | |
def checkFormat(photoPwd): | |
''' | |
检查文件类型是否为图片格式 | |
''' | |
(root, ext) = os.path.splitext(photoPwd) | |
return str.upper(ext[1:]) # 返回文件后缀类型 | |
def getTime(photoName): | |
''' | |
根据文件名特征提取照片拍摄日期,转换为Exif时间格式 | |
from 'IMG_20210422_075810.jpg' to '2024:04:22 07:58:10' | |
''' | |
pN = photoName | |
# from IMG_20210422_075810.jpg to 2024:04:22 07:58:10 | |
imgTime = f'{pN[4:8]}:{pN[8:10]}:{pN[10:12]} {pN[13:15]}:{pN[15:17]}:{pN[17:19]}' | |
return imgTime | |
def setDate(photoName, photoPwd): | |
''' | |
给没有时间的照片加上时间 | |
''' | |
imgTime = getTime(photoName) | |
# 设置Exif信息 | |
exif_dict = piexif.load(photoPwd) # 读取现有Exif信息 | |
exif_dict['0th'][piexif.ImageIFD.DateTime] = imgTime # 注意DateTime在ImageIFD里面 | |
exif_dict['Exif'][piexif.ExifIFD.DateTimeOriginal] = imgTime | |
exif_dict['Exif'][piexif.ExifIFD.DateTimeDigitized] = imgTime | |
exif_bytes = piexif.dump(exif_dict) | |
# 插入Exif信息 | |
piexif.insert(exif_bytes, photoPwd) | |
def changePhotoTime(folder): | |
""" | |
修改该路径下的所有JPG照片的时间 | |
""" | |
for photoName in os.listdir(folder): | |
photoPwd = os.path.join(folder, photoName) # 照片的绝对路径 | |
if checkFormat(photoPwd) == 'JPG': # 如果是JPG | |
setDate(photoName, photoPwd) | |
if __name__ == '__main__': | |
folder = r"D:\DCIM\cloud" # folder: 文件夹路径 | |
changePhotoTime(folder) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment