Using RMagick/ImageMagick in Rails to resize images
The connection between ImageMagick and Rails is done using a gem called RMagick. You can take a look at the User's Guide/API here: RMagick User's Guide. As many of the other Rails developers around, I use a Mac to develop my applications, and then I deploy them in a Linux server. As the Mac installation is perhaps a bit trickier, I'm describing it too.
Installing ImageMagick/RMagick in MacOS X
If you don't have imagemagick already installed, the easiest way to do so is using MacPorts (formerly DarwinPorts). You can follow the instructions on the MacPorts site: Installing MacPorts.
Once you have MacPorts installed, you can easily install ImageMagick issuing the following command in your Terminal (you will be asked for your password):
macbookpro:~ daniel$ sudo port install imagemagick
Now, I'm supposing you already have RubyGems installed.
If not, download the source from RubyForge, compile it with ./configure; make and install it with make install.
So, we can proceed to install the RMagick gem. The tricky part is that you need to set some environment variables to point to the place where the ImageMagick binaries are installed. Open your Terminal, and set the environment variables copying and pasting the following lines:
export MAGICK_HOME=/usr/local/ImageMagick/
export DYLD_LIBRARY_PATH="$MAGICK_HOME/lib/"
export PATH="$MAGICK_HOME/bin:$PATH"
You can now issue the gem install rmagick command which will download, compile and install the RMagick gem automatically.
Installing ImageMagick/RMagick in Linux
The installation under Linux is much easier than in MacOS X. Install ImageMagick and development libraries first and then install the gem (and rubygems too, if you don't have it - apt-get install rubygems -).
newton:~# apt-get install imagemagick libmagick9-dev
newton:~# gem install RMagick
Once you have installed RMagick, using it in your Rails application is as easy as adding the line require 'RMagick' in the controller you need RMagick.
In the following example, we create the preview action in our controller, which will, in a simple way, resize any image to a maximum of 200x200.
def preview
@archive = Archive.find(params[:id])
if @archive.contenttype == "image"
img_orig = Magick::Image.read("/my/picture/path/"+@archive.filename).first
img = img_orig.resize_to_fit(200,200)
@response.headers["Content-type"] = img.mime_type
render :text => img.to_blob
end
end
We could use now this action we created to access the image from another view:
<img src="/archives/preview/<%= @archive.id -%>">
You can take a look at the API to see the complete list of transformations you can do with RMagick: RMagick User's Guide

