Batch resize image with ruby
I was asked to scale and reduce the size of few gigabytes of images, so i picked up my swiss army knife, Ruby.
This will be a quick post and Ruby code snippet i have used to automatically scale and resize those images.
The process is simple just get the images in the folder containing the original images, read in each image, call the “scale” method on the images and save the resized images into a new location.
You can also use the Kernel#sleep method to avoid your CPU to get overloaded.
$ gem install RMagick
require 'rubygems'
require 'RMagick'
# get the folder containing the original images
folder = ARGV[0]
# reduce by 35% = 35/100
scale_by = 0.35
# Get the images in the folder
# (you may replace JPG for whatever extension you will be processing )
files = Dir.glob("#{folder}/*.JPG") do |f|
# read the image
image = Magick::Image.read(f).first
# scale the images
puts "resizing #{image.filename}"
new_image = image.scale(scale_by)
new_image.write("resized/#{image.filename}")
# sleep(5)
end
If anyone has a diferent solution please let me know i would love to know about it.
