Skip to content

Instantly share code, notes, and snippets.

@venkateshshukla
Last active August 29, 2015 14:13
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 venkateshshukla/a20dc30136354dc07037 to your computer and use it in GitHub Desktop.
Save venkateshshukla/a20dc30136354dc07037 to your computer and use it in GitHub Desktop.
Arrange Images as per their timestamps

###Project A small script to arrange the images in the present folders and subfolders as per their time of capture. This would help easing their uploading to google plus photos, making a clean ordered library along the way.

Due to some blunder my images have been shuffled during import and I'd like them to be in order.

###Dependencies

  1. Python 2.7
  2. Python Imaging Library
# A small script to arrange the images in the present folders and subfolders as
# per their time of capture. This would help easing their uploading to google
# plus photos, making a clean ordered library along the way.
from img_exif import get_timestamp
from img_iterator import ImageIterator
img_iter = ImageIterator()
for img in img_iter:
date = get_timestamp(img)
print date
# Extract the timestamp from jpeg images using the exif data present in them
from PIL import Image
from PIL.ExifTags import TAGS
from datetime import datetime
def get_exif_dict(name):
''' Gives back a dictionary of exif name-values of image
:param name: path of the jpeg file
'''
exif = {}
img = Image.open(name)
info = img._getexif()
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
exif[decoded] = value
return exif
def get_time(name):
''' Gives back the original time associated with image
:param name: path of the jpeg file
'''
exif = get_exif_dict(name)
if 'DateTimeOriginal' not in exif.keys():
return None
time = exif['DateTimeOriginal']
return time
def get_timestamp(name):
''' Gives back the timestamp of the image
:param name: path of the jpeg file
'''
time = get_time(name)
if time is None:
return None
date = datetime.strptime(time, "%Y:%m:%d %H:%M:%S")
return int(date.strftime('%s'))
# Class to iterate all jpeg images present in the subfolder
import os
import re
def is_jpeg(name):
s = '\.JPG$'
x = re.search(s, name.upper())
return x is not None
class ImageIterator:
def __init__(self, root = '.'):
self.root = root
self.filelist = []
for root, dirs, files in os.walk(root):
for f in files:
if is_jpeg(f):
self.filelist.append(os.path.join(root, f))
self.count = len(self.filelist)
self.current = 0
def __iter__(self):
return self
def next(self):
if self.current >= self.count:
raise StopIteration
else:
self.current += 1
return self.filelist[self.current - 1]
# Test script to check if class Image Iterator is working or not
from img_iterator import ImageIterator
img_iter = ImageIterator('.')
for img in img_iter:
print img
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment