Sorting photos by date taken

Added on: Wednesday 4th February 2009

I had a bit of a disaster last night whilst trying to get all my digital photos into a web based gallery and needed a quick bit of code to fix it.

The gallery uses a MySQL database and has a facility to index new photos that have been downloaded into a new folder.

Once the images have been indexed by the database they are moved from the download folder and renamed to match the reference in the database.

I made a stupid mistake when using this and managed to rename all the existing photos so that they no longer matched the database reference.

Not a major problem you might think as it is easy to write a quick php script to rename all the files in a folder.

However, the database also contains metadata about the photos and the new filenames no longer sorted into date taken order as they would have done when first indexed.

Exif to the rescue

Luckily, php has a set of functions to extract the 'exif' data from a digital photo and using the read_exif_data function I was able to get the 'DateTimeOriginal' value for each photo.

It was easy enough to load these into an array, sort them and then loop through the array and rename the files.

So 10 minutes later I had my photo gallery back to the state it was in before I messed it up.

I've put the code in a text file for use by anyone who wants to do this.

comments powered by Disqus