Ruby for Batching
September 16th, 2007
The other day I wanted to resize a bunch of images using ImageMagick’s convert command-line utility. I wanted to both resize and change their names from image_name.png to image_name-sm.png, but I couldn’t figure out how to guide ‘convert’ to use part of the original name in the new name. The next obvious tactic would be to use some common shell utilities like ‘for’ and ‘do’. My shell-fu is rusty however, and I still couldn’t get things quite the way I wanted them. Then I think to myself, this would be much easier to do with Ruby.
First, I use ‘puts’ to see if the syntax will come out right:
1 2 3 4 5 6 |
irb(main):017:0> Dir['*.png'].each { |f| puts "convert #{f} -resize 400x400 #{f[0..-5]}-sm.png" } convert character_creation.png -resize 400x400 character_creation-sm.png convert battle-mountain_pass.png -resize 400x400 battle-mountain_pass-sm.png convert loot-drag_and_drop.png -resize 400x400 loot-drag_and_drop-sm.png convert market.png -resize 400x400 market-sm.png ...(etc)... |
Then I just run the same line with system instead of puts:
Dir['*.png'].each { |f| system "convert #{f} -resize 400x400 #{f[0..-5]}-sm.png" } |
With a little practice, this can be done on the command line - who needs shell scripting?
1 2 |
# run from the shell prompt: ruby -e 'Dir["*.png"].each { |f| system "convert #{f} -resize 400x400 #{f[0..-5]}-sm.png" }' |


Sorry, comments are closed for this article.