Skip to content

Instantly share code, notes, and snippets.

@danielpclark
Created September 1, 2012 20:56
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 danielpclark/3587018 to your computer and use it in GitHub Desktop.
Save danielpclark/3587018 to your computer and use it in GitHub Desktop.
Resize all images in a directory into a subfolder
#!/usr/bin/ruby
# resize usage:
# resize <folder> <image type> <scale>
# IE: resize ./ *.JPG 35
# Attribution:
# Original version of code was written by Joao Silva
# Available at http://codedefinition.com/batch-resize-image-with-ruby.html
# Update by Daniel P. Clark on 08/31/2012 <webmaster@6ftdan.com>
require 'rubygems'
require 'RMagick'
# get the folder containing the original images
folder = "./"
# and the extension type
extension = "*.JPG"
if not ARGV[0].nil?
if File.directory?(ARGV[0])
folder = ARGV[0]
if not folder[-1..-1] == "/"
folder << "/"
end
end
if not ARGV[1].nil?
if !!ARGV[1][/\*\..../] and ARGV[1].length >= 5
extension = ARGV[1]
end
end
end
# reduce by 35% = 35/100
scale_by = 0.35
# get scale size
if ARGV.last[/\d\d/].length == 2 and ARGV.last.length == 2
scale_by = ARGV.last.to_f/100
end
outfolder = "resized/"
Dir.mkdir(outfolder) unless File.exists?(outfolder)
# Get the images in the folder
Dir.glob("#{folder + extension}") do |f|
# read the image
image = Magick::Image.read(f).first
# scale the images
puts "Resizing #{image.filename} on a scale of #{(scale_by*100).to_i}% to #{folder + outfolder + image.filename} "
new_image = image.scale(scale_by)
new_image.write(outfolder + image.filename)
# IMPORTANT!!! # Free up memory as this image won't be worked on again.
[image,new_image].each { |img| img.destroy! }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment