Last active
July 18, 2019 09:03
-
-
Save cgoldberg/8474158 to your computer and use it in GitHub Desktop.
Python - image metadata remover and date fixer.
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
#!/usr/bin/env python | |
# | |
# image metadata remover and date fixer. | |
# Corey Goldberg, 2014 | |
"""Recursively scan a directory tree for image files, and fix metadata. | |
* removes all metadata (Exif, IPTC, XMP, GPS Info, comment, thumbnail) | |
* sets metadata and file timestamps to oldest datetime found. | |
* works with .jpg and .png formats | |
* modifications are done in-place. | |
Requires: gexiv2 (GObject-based wrapper around the Exiv2 library) | |
Install gexiv2 on Ubuntu/Debian: sudo apt-get install gir1.2-gexiv2-0.4 | |
""" | |
import os | |
import time | |
from gi.repository import GExiv2 | |
DATE_PATTERN = '%Y:%m:%d %H:%M:%S' | |
def fix_image_dates(img_path): | |
ct = os.path.getctime(img_path) | |
ctime = time.strftime(DATE_PATTERN, time.localtime(ct)) | |
mt = os.path.getmtime(img_path) | |
mtime = time.strftime(DATE_PATTERN, time.localtime(mt)) | |
exif = GExiv2.Metadata(img_path) | |
try: | |
dtime = exif['Exif.Image.DateTime'] | |
except KeyError: | |
dtime = None | |
try: | |
dtime_digitized = exif['Exif.Photo.DateTimeDigitized'] | |
except KeyError: | |
dtime_digitized = None | |
try: | |
dtime_original = exif['Exif.Photo.DateTimeOriginal'] | |
except KeyError: | |
dtime_original = None | |
oldest_time = sorted( | |
[x for x in (ctime, mtime, dtime, dtime_digitized, dtime_original) | |
if x is not None] | |
)[0] | |
exif.clear_comment() | |
exif.clear_exif() | |
exif.clear_iptc() | |
exif.clear_xmp() | |
exif.delete_gps_info() | |
exif.erase_exif_thumbnail() | |
exif.clear() | |
exif['Exif.Image.DateTime'] = oldest_time | |
exif['Exif.Photo.DateTimeDigitized'] = oldest_time | |
exif['Exif.Photo.DateTimeOriginal'] = oldest_time | |
exif.save_file() | |
epoch = int(time.mktime(time.strptime(oldest_time, DATE_PATTERN))) | |
os.utime(img_path, (epoch, epoch)) | |
return oldest_time | |
if __name__ == '__main__': | |
dir = '.' | |
for root, dirs, file_names in os.walk(dir): | |
for file_name in file_names: | |
if file_name.lower().endswith(('jpg', 'png')): | |
img_path = os.path.join(root, file_name) | |
print('-' * 40) | |
print(img_path) | |
print(fix_image_dates(img_path)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment