Last active
October 24, 2017 11:41
-
-
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/
This file contains 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
#!/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