require 'rubygems' require 'RMagick' class ImageResizer def initialize(load_path = ".", save_path = ".") @load_path = load_path @save_path = save_path Dir.mkdir(@save_path, 0755) unless FileTest.directory?(@save_path) @images = Dir.glob( @load_path + "/*.{jpeg,jpg}", File::FNM_CASEFOLD) end def resize(scales) # mkdir the sub direcotries to save images scales.each do |key, scale| Dir.mkdir(@save_path + "/" + key, 0755) unless FileTest.directory?(@save_path + "/" + key) end # Resize images and save them to sub directories @images.each do |image| original = Magick::Image.read(image).first width = original.columns height = original.rows scales.each do |key, scale| width > height ? ratio = scale["yoko"].to_f / width : ratio = scale["tate"].to_f / width # resized = original.resize_to_fit ( scale["yoko"], scale["tate"] ) resized = original.resize(ratio) resized.write(image.sub(@load_path, @save_path + "/" + key)) {self.quality = 80} end GC.start end end end # 画像を縮小する際のパラメーターを、scalesで指定。 # large, small など複数のハッシュを指定することで、複数のサイズの画像を出力 # 各画像は、ハッシュのKey名のディレクトリに出力されます。 # 画像のサイズの指定は、画像の横の長さをピクセルで指定 # yoko は横長画像、 tate は縦長画像の場合の、画像の横幅を指定 scales = { "large" => {"yoko" => 800, "tate" => 400}, "small" => {"yoko" => 500, "tate" => 250} } resizer = ImageResizer.new(ARGV[0], ARGV[1]) resizer.resize(scales) exit