I’m working on a little command line tool for generating HTML photo galleries and needed to resize some images with RMagick. Unfortunately there were a shortage of good, concise examples of how to use it. So, for my own future reference and yours, here’s how to resize an image to maximum dimensions while preserving its aspect ratio. You can provide a width and height to resize_to_fit, or just one value as I am here.
require 'rmagick'
# Read first image from file
image = Magick::Image::read(image_path).first
# Resize image to maxium dimensions
image.resize_to_fit!(250)
# Write image to file system
image.write(thumb_path)
# Free image from memory
image.destroy!
In this example, we’re reading an image, resizing it, and then writing it to a new path. Do make sure you write it to a new path so that you don’t overwrite all your images. That would be sad.
Alternatively, you can use resize_to_fill to have the image fill the dimensions provided. This is great for generating square crops of your images.
image.resize_to_fill!(250)
The destroy method also turns out to be quite important. Because the Ruby garbage collector doesn’t know how much memory is being used inside of ImageMagick, the library underlying RMagick, it doesn’t garbage collect often enough. This can turn into a big problem if you’re resizing a large number of images in a loop. Fortunately it’s easy to address.
image.destroy!
Lastly, if you’re working with JPGs and would like to change the quality, you can pass a block to write.
image.write(thumb_path) { self.quality = 75 }
RMagick is great and does all kinds of neat stuff. Now that you’re up and running, take a look at the rest of the instance methods for more cool image manipulation goodness.



