Skip to content

Instantly share code, notes, and snippets.

@calebwoods
Last active October 24, 2017 11:41
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calebwoods/714731713935bd2b3625 to your computer and use it in GitHub Desktop.
Save calebwoods/714731713935bd2b3625 to your computer and use it in GitHub Desktop.
Script for resizing a directory of images using Ruby. Note requires the RMagick gem to be installed and assumes Rbenv is used for managing the Ruby Version. Blog post: http://www.calebwoods.com/2015/02/01/batch-resizing-images-ruby/
#!/usr/bin/ruby
require 'RMagick'
require 'pathname'
@directory = Pathname(File.expand_path(ARGV[0]))
@size = ARGV.fetch(1) { 1025 }
def resize_image(file)
img = Magick::Image.read(file).first
resized = img.resize_to_fit(@size)
resized_path = @directory.join('resized', File.basename(file))
resized.write(resized_path) do
self.quality = 100
end
# free up RAM
img.destroy!
resized.destroy!
end
resize_dir = "#{@directory}/resized"
unless File.directory? resize_dir
puts "Creating #{resize_dir}/"
Dir.mkdir resize_dir
end
files = Dir.glob "#{@directory}/*.{jpg,png,gif}"
puts "Resizing #{files.size} images..."
files.each do |file|
puts "Resizing #{file}"
resize_image(file)
end
puts "Finished resizing #{files.size} images"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment