How to get Exif data from a jpeg file

BJ Swope bigblueswope at gmail.com
Mon May 18 14:20:51 EDT 2009


On Sun, May 17, 2009 at 4:17 AM, Arnaud Delobelle
<arnodel at googlemail.com> wrote:
>
> Daniel Fetchinson <fetchinson at googlemail.com> writes:
>
> >> I need to get the creation date from a jpeg file in Python.  Googling
> >> brought up a several references to apparently defunct modules.  The best
> >> way I have been able to find so far is something like this:
> >>
> >> from PIL import Image
> >> img = Image.open('img.jpg')
> >> exif_data = img._getexif()
> >> creation_date = exif_data[36867]
> >>
> >> Where 36867 is the exif tag for the creation date data (which I found by
> >> ooking at PIL.ExifTags.TAGS).  But this doesn't even seem to be
> >> documented in the PIL docs.  Is there a more natural way to do this?
> >
> >
> > Have you tried http://sourceforge.net/projects/exif-py/ ?
> >
> > HTH,
> > Daniel
>
> I will have a look - thank you.
>
> --
> Arnaud
> --
> http://mail.python.org/mailman/listinfo/python-list


I use the EXIF module to do bulk renames of all the pictures in a directory.

Here's my hackeration...



import sys
import os
import re
import time
import win32file
import datetime
import EXIF

DATE_FORMAT   = '%Y%m%d_%H%M%S'
allowed_files = ['.asf', '.jpg', '.mod', '.mov', '.mpeg', '.mpg',
'.jpeg', '.png', '.tiff', '.tif']
named_files = []

r = re.compile('.mod',)

def is_a_file(path, file, xtn):
    """
    We only want to rename the files right?
    Return True or False depending on whether object is a file or a directory
    """

    if os.path.isdir(os.path.join(path,file)):
        print "This is a directory not a file.  Will not rename!"
        return False
    if allowed_files.count(xtn):
        return True
    else:
        print file, "is not a in the list of allowed extensions. Will
not rename!"
        return False


def renameFile(path, file):
    """ Rename <old_filename> with the using the date/time created or
modified for the new file name"""

    old_filename = os.path.join(path,file)

    (name,xtn) = os.path.splitext(file)
    xtn = xtn.lower()

    if re.search(r, xtn):
        xtn_old = xtn
        xtn = '.mpg'
        print xtn_old, 'changed to', xtn

    if is_a_file(path, file, xtn):
        created_time = os.path.getctime(old_filename)
        modify_time = os.path.getmtime(old_filename)

        f = open(old_filename, 'rb')
        try:
            tags=EXIF.process_file(f)
        except UnboundLocalError:
            print "No EXIF data available for ", file
            tags = {}
            exif_time = 0
        try:
            tags['EXIF DateTimeOriginal']
            exif_time = str(tags['EXIF DateTimeOriginal'])
            exif_time = int(time.mktime(time.strptime(exif_time,
"%Y:%m:%d %H:%M:%S")))
        except (KeyError,ValueError):
            print 'No EXIF DateTimeOriginal for ', file
            exif_time = 0
        f.close()

        if created_time < modify_time:
            local_time = time.localtime(created_time)
        else:
            local_time = time.localtime(modify_time)

        if exif_time:
            if exif_time < local_time:
                local_time = time.localtime(exif_time)

        date_time_name = time.strftime(DATE_FORMAT, local_time)

        copy_number = named_files.count(date_time_name)
        named_files.append(date_time_name)

        new_name = date_time_name + "_" + str(copy_number) + xtn

        new_filename = os.path.join(path, new_name)

        print 'Renaming:', old_filename, 'to', new_filename
        #print 'Created Time  = ', created_time
        #print 'Modified Time = ', modify_time
        #print 'EXIF Time     = ', exif_time
        #print 'Time Used     = ', local_time
        os.rename(old_filename, new_filename)


if __name__ == '__main__':
    if os.path.isdir(sys.argv[1]):
        """Recursively walk the directory listed as Arg 1 and work each file."""
        print
        for path,dirs,files in os.walk(sys.argv[1]):
            for file in files:
                renameFile(path, file)
    else:
        print "\nNo path to rename specified.\n"
        print "Usage:\n\tpython", sys.argv[0], "<path to directory of
source files>"
        sys.exit(1)




--
We are all slave to our own paradigm. -- Joshua Williams

If the letters PhD appear after a person's name, that person will
remain outdoors even after it's started raining. -- Jeff Kay

Fascism is a term used to describe authoritarian nationalist political
ideologies or mass movements that are concerned with notions of
cultural decline or decadence and seek to achieve a millenarian
national rebirth by exalting the nation or race, and promoting cults
of unity, strength and purity. - Wikipedia

The story of postwar American conservatism is best understood as a
continual replay of a single long-standing debate. On one side are
those who have upheld the Burkean ideal of replenishing civil society
by adjusting to changing conditions. On the other are those committed
to a revanchist counterrevolution, the restoration of America's
pre-welfare state ancien regime. And, time and again, the
counterrevolutionaries have won. The result is that modern American
conservatism has dedicated itself not to fortifying and replenishing
civil society but rather to weakening it through a politics of civil
warfare. -- Sam Tanenhaus



More information about the Python-list mailing list