Suffix

Published by Simon Schoeters

Installing ImageMagick & RMagick for RoR on Mac OS X

Update: Check out this great installation script by Solomon White if you are running Snow Leopard. It worked perfect here.

ImageMagick is a command line utility to convert, edit and compose images that is typically used in combination with a programming language. The Ruby interface is called RMagick. The RMagick interface makes image editing in Ruby painless, if you get it installed that is. GraphicsMagick is another image editor that can be used in combination with RMagick but I didn't look into that.

There are numerous ways to get ImageMagick and RMagic installed on Mac OS X and I don't even remember all the different ways I tried but the following method seems to work. MacPorts may install versions of the software that are out-of-date, so check this first if that's an important issue for you.

MacPorts

Let's start with installing MacPorts, formerly called DarwinPorts. This port automatically installs ImageMagick and all the dependent libraries. You need Xcode installed for MacPorts to work. Installing MacPorts is very straightforward and shouldn't be a problem, download the newest MacPorts-x.x.x.dmg and install the package.

Once MacPorts is installed you can install ImageMagick via Terminal. The path to the port binary may be different but I suppose it's the default installation directory, isn't it?

sudo /opt/local/bin/port install ImageMagick

This may take a while and you'll see MacPorts downloading and installing ImageMagick, done? Let's get on with RMagick the same way we got ImageMagick:

sudo /opt/local/bin/port install rb-rmagick

Again, waiting, I think it took about 15 minutes to finish.

Gem

Next we'll need the RMagick gem as well. Note: Installing the RMagick gem worked find on my old PPC Mac but didn't work on the newer i386 (Intel) as the RMagick gem is built with the PPC headers. To install the gem set your ARCHFLAGS to i386 first. Here is how:

export ARCHFLAGS='-arch i386'
gem install rmagick

As Jelle points out you may want to add the local bin folder to your PATH. This will make it easier to run RMagick stuff that's installed in that directory without the need to specify the whole path each time. Add the following line to your .bash_login file and restart Terminal.

vi ~/.bash_login
export PATH="/opt/local/bin/:$PATH"

Sample conversion

Once this is done we can run a quick Ruby script to check if the installation went smoothly. Create the following create_thumb.rb script:

#!/usr/bin/env ruby
require 'RMagick'
img = Magick::Image.read('myimage.jpg').first
thumbnail = img.crop_resized(50, 50)
thumbnail.write 'myimage_thumb.jpg'

This creates a thumbnail image of 50px × 50px from the myimage.jpg file and saves it as myimage_thumb.jpg. Make sure you have a JPEG image in the same directory and run the script.

ruby create_thumb.rb

That's it, you should see a new file appearing in the current directory proving that it works!