Created
January 28, 2010 21:01
-
-
Save kblake/289138 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'image_size' #imagesize.rubyforge.net | |
=begin | |
This is a small test script that I wrote to play around with Ruby's directory | |
and file handling. | |
The scenario is this... I have a directory structure as follows: | |
/rename.rb | |
/testing | |
/merchant1 | |
/logo.jpg | |
/logo_homepage.jpg | |
/logo_landing.jpg | |
/merchant2 | |
/logo.jpg | |
/logo_homepage.jpg | |
/logo_landing.jpg | |
/merchant3 | |
/logo.jpg | |
/logo_homepage.jpg | |
/logo_landing.jpg | |
/etc.. | |
The goal is to go through each directory (the directory structure is standard, | |
so there's no need for recursion) and test each JPEG image from the hash | |
(files_to_rename) for proper width. If the width is correct (as defined in | |
the hash), then rename it to the new name as defined in the hash. | |
=end | |
# Directory we're using | |
directory = 'C:/ruby_projects/file_rename/testing/' | |
# Files to exclude from the directory listing | |
files_to_exclude = ['.','..'] | |
# Files that we're testing and name changing | |
files_to_rename = { | |
# current filename => [new filename, required img width] | |
'logo.jpg' => ['logo_300.jpg',300], | |
'logo_homepage.jpg' => ['logo_280x45.jpg',280], | |
'logo_landing.jpg' => ['logo_728x90.jpg',728] | |
} | |
# Get the directory list | |
Dir.chdir(directory) # Navigate to directory | |
directory_listing = Dir.entries('.') # Get directory listing | |
directory_listing.delete_if {|fn| files_to_exclude.include?(fn) } # Delete excluded files | |
directory_listing.delete_if {|fn| !File.directory?(fn) } # Delete non-directories | |
# Process each directory | |
directory_listing.each do |dir| | |
# Navigate to dir | |
Dir.chdir(directory + '/' + dir + '/') | |
# Get all the .jpg files from dir | |
images = Dir.glob('*.jpg') | |
# Begin renaming logic | |
images.each do |img| | |
# Check if we're trying to rename this particular image | |
if files_to_rename.include?(img) | |
# Get the image's dimensions | |
raw_img = File.open(img,'rb') {|i| i.read } # Open image | |
img_size = ImageSize.new(raw_img).get_size # Get image dimensions | |
# Check the width to make sure it's correct | |
if files_to_rename[img][1] == img_size[0] | |
# The width is correct, so rename it as desired | |
File.rename(img,files_to_rename[img][0]) | |
else | |
# Width doesn't match, so rename with a flag for manual resizing | |
File.rename(img,'RESIZE_' + files_to_rename[img][0]) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment