I have seperated the script in to files. The first is a gallery class
that do all the work, and the second is a file to get the user input
form the consol. I am going to use the class later on in my Ruby On
Rails library. But for now a console script is ok.
gallery.rb
require "ftools"
require 'RMagick'
class Gallery
include Magick
attr_accessor :source_dir , :target_dir, :name, :picture_width, :thumbnail_width, :copy_org_pic
def initialize()
@source_dir = source_dir
@target_dir = target_dir
@name = name
@picture_width = picture_width
@thumbnail_width = thumbnail_width
@copy_org_pic = copy_org_pic
end
def pictures
Dir.new(source_dir).to_a.delete_if { |f| f !~ /(jpg|gif|png)$/i }
end
def create_dir(path)
Dir.mkdir(path ,0755) unless File.exist?(path)
end
def create_dirs()
gallery_path = "#{@target_dir}/#{@name}/"
puts "abc: path:" + gallery_path
create_dir(gallery_path)
create_dir("#{gallery_path}thumbnails")
create_dir("#{gallery_path}originals") if copy_org_pic
end
def create
create_dirs()
pictures.each do |picture|
puts picture
File.cp("#{source_dir}/#{picture}", "#{@target_dir}/#{@name}/originals/#{picture}") if copy_org_pic
# Open the image-file
img = Image.read("#{source_dir}/#{picture}").first
# Create thumbnail dir if it does not exist
thumbnail_name = "#{target_dir}/#{@name}/thumbnails/#{picture}"
picture_name = "#{target_dir}/#{@name}/#{picture}"
# If the images is in landscape format we use the image-width to calculate
if img.columns > img.rows
thumbnail_factor = (thumbnail_width.to_f / img.columns )
picture_factor = (picture_width.to_f / img.columns )
else
thumbnail_factor = (thumbnail_width.to_f / img.rows )
picture_factor = (picture_width.to_f / img.rows )
end
thumb = img.scale(picture_factor )
thumb.write(picture_name )
thumb = img.scale(thumbnail_factor )
thumb.write(thumbnail_name )
end
end
end
require 'gallery'
puts "\nEnter the source directory:"
str_source_dir = gets.chop #Remove newline from string
while File.exist?(str_source_dir) == false
puts str_source_dir + " does not exist, try again"
str_source_dir = gets.chop
end
gallery = Gallery.new
gallery.source_dir = str_source_dir
gallery.copy_org_pic = false
puts "There is #{gallery.pictures.length.to_s} pictures in the directory: #{str_source_dir}"
puts "\nEnter the taget directory:"
str_target_directory = gets.chop #Remove newline from string
while File.exist?(str_target_directory ) == false
puts str_target_directory + " does not exist, try again"
str_target_directory = gets.chop
end
gallery.target_dir = str_target_directory
puts "and the name of the gallery is?"
gallery.name = gets.chop
puts "Enter the max width of the presentation picture"
gallery.picture_width = gets
puts "Enter the max width of the thumbnails"
gallery.thumbnail_width = gets
gallery.create()