Skip to content

Instantly share code, notes, and snippets.

@vfrico
Created March 15, 2017 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vfrico/208d12f4ae42699c8f69337325941467 to your computer and use it in GitHub Desktop.
Save vfrico/208d12f4ae42699c8f69337325941467 to your computer and use it in GitHub Desktop.
Reorder images by EXIF date under same prefix
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# coding:utf-8
#
# rename_images_to_list.py: Reorder images by EXIF date under same prefix
# Copyright (C) 2017 Víctor Fernández Rico <vfrico@gmail.com>
#
# Thanks to Denis Barmenkov <denis.barmenkov@gmail.com>, for the original idea
# https://code.activestate.com/recipes/576646-exif-date-based-jpeg-files
# -rename-using-pil/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from PIL import Image
import os
import re
import sys
import time
def extract_time(image_file):
if not os.path.isfile(image_file):
return None
im = Image.open(image_file)
if hasattr(im, '_getexif'):
exifdata = im._getexif()
ctime = exifdata[0x9003]
return ctime
return None
def rename_list(image_list):
all_images = []
for image in image_list:
all_images.append((image, extract_time(image)))
reorder = sorted(all_images, key=lambda image: image[1])
count = 1
for image in reorder:
new_path = rename_file(image[0], str(count), "EON")
os.rename(image[0], new_path)
count += 1
def rename_file(image_file, position, prefix):
path, base = os.path.split(image_file)
name, ext = os.path.splitext(base)
new_name = "{0}_{1}{2}".format(prefix, position, ext)
return os.path.join(path, new_name)
if __name__=='__main__':
if len(sys.argv) > 1:
path = sys.argv[1:]
rename_list(path)
else:
help_ = ("Modo de empleo:\n"
"\t" + sys.argv[0] + ": images.jpg")
print(help_)
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment