Skip to content

Instantly share code, notes, and snippets.

@FiXato
Last active December 22, 2015 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FiXato/6501776 to your computer and use it in GitHub Desktop.
Save FiXato/6501776 to your computer and use it in GitHub Desktop.
Renames images to their IPTC captions, suffixing them with the original filename as well. Example: 1-bar.jpg => bar-to-the-awesome - 1-bar.jpg Very hacky, but it scratched my itch and might help someone else too. :)
# encoding: utf-8
# Renames images to their IPTC captions, suffixing them with the original filename as well.
# Example:
# 1-bar.jpg => bar-to-the-awesome - 1-bar.jpg
# Very hacky, but it scratched my itch and might help someone else too. :)
require 'fileutils'
require 'iptc'
FileUtils.cd("path/to/source/images")
output_dir = "renamed"
FileUtils.mkdir(output_dir) unless File.exist?(output_dir)
errored_files = {}
Dir.glob("*.jpg").each do |file|
puts "Processing #{file}:"
begin
image = IPTC::JPEG::Image.from_file(file)
caption = image.values['iptc/Caption'].value.gsub(/\s/,' ').strip
unless caption or caption == ''
puts " Couldn't find caption. Skipping #{file}"
next
end
puts " Found caption: #{caption}"
new_name = File.join(caption + ' - ' + File.basename(file))
new_name = new_name.gsub(' & ', ' en ').gsub('&', ' en ').gsub(/[\/\!*]/, '-').gsub('?', ' misschien')
new_name = File.expand_path(File.join('.', output_dir, new_name))
if new_name.size > 255
puts " Filepath too large: #{new_name.size} characters. Trimming!"
ending = new_name[-16..-1]
new_name.gsub!(/#{ending}\z/,'')
new_name = new_name[0..249] + ending
puts " Filepath trimmed to #{new_name.size} characters: #{new_name}"
end
puts " Copying #{file} to #{new_name}"
FileUtils.cp(file,new_name)
rescue Exception => e
errored_files[File.basename(file)] = {'source' => file, 'target' => (new_name rescue nil), 'error' => e}
puts " Error with #{file}:"
puts " #{e.to_yaml}"
end
puts " ------"
end
puts 'Errors:'
errored_files.each do |filename, data|
puts "#{filename}:"
puts " source: #{data['source']}"
puts " target: #{data['target']}"
puts " error:"
puts " #{data['error'].to_yaml}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment