Sorting photos by timestamp with Perl

My digital picture frame does a slideshow in filename order. I have hundreds of pictures taken over several years on different cameras with different file naming schemes. I've even rolled over the counter on one of the cameras, so I might have IMG1234.jpg twice (saved in different directories).

Here's how I used Perl to rename these pictures into the right order based on the timestamp metadata inside the JPEG files:

#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;
use autodie;
use Digest::MD5 'md5_hex';
use Image::ExifTool 'ImageInfo';
use Path::Class;

for my $f ( dir()->children ) {
  next if $f->is_dir;
  my $exif = Image::ExifTool->new;
  $exif->ExtractInfo($f->stringify);
  my $date = $exif->GetValue('DateTimeOriginal', 'PrintConv');
  next unless defined $date;
  $date =~ tr[ :][T-];
  my $digest = md5_hex($f->slurp);
  $digest = substr($digest,0,7);
  my $new_name = "$date-$digest.jpg";
  unless ( $f->basename eq $new_name ) {
    rename $f => $new_name;
    say "renamed $f => $new_name";
  }
}

This program renames everything in the current directory into a format like this "2011-05-28T14-48-20-7fc2e71.jpg" -- which is an ISO8601 datetime (with "-" instead of ":") plus the first 7-hex-characters of an MD5 checksum. I use the checksum on the off-chance that two pictures were taken at the exact same second (e.g. from two cameras) or that one picture was a cropped/retouched version of an original. Anything that doesn't have EXIF datetime information is skipped and then I have to examine those manually to sort them into the rest.

It's not much, but it's quick and it worked.

This entry was posted in perl programming and tagged , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

2 Comments

  1. Posted July 24, 2011 at 8:36 am | Permalink

    Thanks! My parents asked me to do something like this. Now the work is done by you ;-)

  2. Posted July 24, 2011 at 2:47 pm | Permalink

    Nice example of how to use Perl for something that anyone - even non programmers - need.

    If someone could add a nice GUI wrapper around this and include in a Perl distribution for Windows...

One Trackback

© 2009-2014 David Golden All Rights Reserved