Saturday, August 07, 2010

Using RMagick to Resize Pics

I wanted to upload our beach pics to Facebook, but I didn't want the Facebook system to have to resize the pics. From what I could determine, Facebook has a limitation on photo sizes of 720 pixels on the largest side. Also some of the pics needed to be re-oriented.

The tool that I used to do accomplish this task under Linux is called ImageMagick. ImageMagick provides some nice command line tools for working with pics. However, I didn't want to have to write complex bash scripts to accomplish this task so I decided to use Ruby and RMagick. (Ruby, ImageMagick, and RMagick are available for Windows as well.)

Below is the script that I ended up using. It reads the name of the file to be resized from the command line. If the camera adds orientation information to the image, the script will orient it in the proper direction. After orienting the image, it will constrain the image to a maximum of 720 on each side while maintaining the aspect ratio. This means that it will stretch or shrink the side in a manner that distorts the image.


Name: resize.rb

#!/usr/bin/ruby

require 'RMagick'
include Magick

ARGV.each { |filename|
origpic = Image::read(filename).first

newpic = origpic.auto_orient
origpic.destroy!
newpic.resize_to_fit!(720)
newpic.write("lores_"+filename)
newpic.destroy!
}

Usage:
reseize.rb image.jpg
or
resize.rb *.jpg



Note that I'm using the destroy! option. This tells the libraries to release the memory that the image was using. Otherwise, running this script on a directory of images will quickly consume all of the memory and make the computer slower and slower. I discovered this the hard way. I had expected it to release the memory after each trip through the loop. It didn't work that way.

No comments: