Using RMagick and EXIF to get the date a photo is taken in Rails
Posted: February 12, 2008 Filed under: Rails 2 CommentsWow, it’s been a long time since my last Rails-related post (actually months). That’s because it’s been about that long since I’ve done much in the way of Rails development. Over the past few weeks, I’ve been rebuilding my personal website in Rails 2.0, which (per my wife’s requirements) will include a photo gallery.
My Photo
class utilized attachment_fu to easily support image uploads. I also wanted to be able to display the date the photo was taken, not the date is was uploaded. This information is encoded in the JPEG image file by the digital camera, we just need to pull it out. Although there are several methods to do this, I chose to use RMagick as it is already included in my application for attachment_fu. We can use the get_exif_by_entry
method to get this (as well as a great deal of other) information:
class Photo < ActiveRecord::Base @@exif_date_format = '%Y:%m:%d %H:%M:%S' cattr_accessor :exif_date_format # some stuff def date_taken photo = Magick::Image.read(full_filename).first # the get_exif_by_entry method returns in the format: [["Make", "Canon"]] date = photo.get_exif_by_entry('DateTime')[0][1] return unless date DateTime.strptime(date, exif_date_format) end #some more stuff end
That’s it. Read the EXIF information, provide it’s format, and create a new DateTime
object.
Thanks for the tip – very useful 🙂
It works perfectly. Thanks a lot.