Sorting photos by timestamp with Perl

Reading time: 2 minutes

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.

•      •      •

If you enjoyed this or have feedback, please let me know by or