4/30/11

Ruby 1.9.1 - Change JPG image name using EXIF information.

Recently I got a lot of images from a trip. Pictures I've received were from a different cameras.

I wanted to create a chronological photo gallery.

Unfortunately when I copied the files, I realized that all of them have the same date and time and different prefixes.

Fortunately I've noticed that all images I got, contains EXIF JPG information.

That is why I've created a ruby script, which changes images names, using Date Time, taken from EXIF information.

To read EXIF information use ruby exifr gem.

gem install exifr

Here is a code. Enjoy!

require 'rubygems'
require 'exifr'

inputDir = ARGV[0]
prefix = ARGV[1].nil? ? "IMG" : ARGV[1]

if (ARGV.length >= 1) 
 Dir.glob("#{inputDir}/*.jpg",File::FNM_CASEFOLD).each() {|file|

  timeTaken = EXIFR::JPEG.new(file).date_time

  if (timeTaken.nil? & !EXIFR::JPEG.new(file).exif.nil?)
   timeTaken = EXIFR::JPEG.new(file).exif.date_time_original
  end
  
  if (timeTaken.nil?)
   timeTaken = File.mtime(file)
  end


  if (!timeTaken.nil?)
   filename = "#{inputDir}/#{prefix}_#{timeTaken.strftime('%Y%m%d_%H%M%S')}.JPG"

   puts "RENAME: #{file} -> #{filename}"
   if(!File.exist?(filename))
    File.rename(file,filename)
   else
    puts "ERROR: FILE #{filename} ALREADY_EXISTS!!!!"
   end
  else
   puts "ERROR: Can't get time for #{file}"
  end

 }
else
 puts "JPG_RENAME.rb #IMAGES_FOLDER [FILE_NAME_PREFIX]"
end
Latest version gan be found here https://bitbucket.org/chesti/jpgrename

1 comment: