Ruby on Rails 2.1 - RMagick Guide
Rails provides bindings to ImageMagick and GraphicsMagick, which are popular and stable C libraries. The RMagick library provides the same interface against ImageMagick and GraphicsMagick, so it does not matter which one you use.
You can get RMagick by installing the rmagick gen on Unix or rmagick-win32 gem on Windows. Let's install it on a Unix machine as follows −
$ gem install rmagick
The RMagick module comes along with class Magick::Image, which lets you resize images in four different methods −
- resize(width, height)
- scale(width, height)
- sample(width, height)
- thumbnail(width, height)
All these methods accept a pair integer values, corresponding to the width and height in pixels of the thumbnail you want.
Here's an example that uses resize() method to resize the image. It takes the file tmp.jpg and makes a thumbnail of it 100 pixels wide by 100 pixels tall −
require 'rubygems' require 'RMagick' class ImageController < ApplicationController def createThubnail width, height = 100, 100 img = Magick::Image.read('tmp.jpg').first thumb = img.resize(width, height) # If you want to save this image use following # thumb.write("mythumbnail.jpg") # otherwise send it to the browser as follows send_data(thumb.to_blob, :disposition => 'inline', :type => 'image/jpg') end end
Here are the steps to create a thumbnail −
Here the class method Image.read receives an image filename as an argument and returns an array of Image objects. You obtain the first element of that array, which is obviously our tmp.jpg image.
Next, we are calling method resize with the desired arguments, which is creating a thumbnail.
Finally, we are directing this image to the browser. You can also use the method thumb.write("mythumbnail.jpg") to store this image locally at your machine.
Converting Image Formats
It is very easy to convert an image file from one format to another format. RMagick handles it very smartly. You can just read in the file and write it out with a different extension.
The following example converts a JPEG file into a GIF file −
require 'rubygems' require 'RMagick' class ImageController < ApplicationController def changeFormat img = Magick::Image.read('tmp.jpg').first # If you want to save this image use following # img.write("mythumbnail.gif") # otherwise send it to the browser as follows send_data(img.to_blob, :disposition => 'inline', :type => 'image/gif') end end
You can change an image to a format based on your requirement as follows −
img = Magick::Image.read("tmp.png").first img.write("tmp.jpg") # Converts into JPEG img.write("tmp.gif") # Converts into GIF img.write("JPG:tmp") # Converts into JPEG img.write("GIF:tmp") # Converts into GIF