RMagick User's Guide and Reference
How to use RMagick

Table Of Contents

Basic concepts

Let's look at the RMagick equivalent of "Hello, world". This program reads an image file named "Cheetah.jpg" and displays it on your monitor.

1. require 'RMagick'
2. include Magick
3.
4. cat = ImageList.new("Cheetah.jpg")
5. cat.display
6. exit

Line 1 requires the RMagick.rb file, which defines the Magick module. The Magick module contains 3 major classes, ImageList, Image, and Draw. This section - Basic Comcepts - describes the ImageList and Image classes. The Draw class is explained in the Drawing on and adding text to images section, below.

The statement on line 5 creates an imagelist object and initializes it by reading the Cheetah.jpg file in the current directory. Line 6 sends the display method to cat. When you send display to an imagelist, it causes all the images in the imagelist to be displayed on the default X Window screen. In this case, the display method makes a picture of a cheetah appear on your monitor.

Type this program in and try running it now. The Cheetah.jpg file is in the ex/images subdirectory where you installed the RMagick documentation.

Let's talk about RMagick's Image and ImageList classes. An Image object describes one image or one frame in an image with multiple frames. (An animated GIF or a Photoshop image with multiple layers are examples of images with multiple frames.) You can create a image object from an image file such as a GIF, PNG, or JPEG. You can create a image from scratch. You can write an image to disk, display it on a screen, change its size or orientation, convert it to another format, or otherwise modify it using one of over 100 Image methods.

An ImageList object is a list of images. It contains zero or more images and a scene number. The scene number indicates the current image. ImageList methods operate on all the images in the list. Also, with a very few exceptions, any method defined in the Image class can be used as well. Since Image methods always operate on a single image, when an Image method is sent to an imagelist, the ImageList class sends the method to the current image, that is, the image specified by the scene number.

The ImageList class is a subclass of the Array class, so you can use most Array methods to change the images in the imagelist. For example, you can use the << method to add images to the list.

Going back to the example, let's make one modification.

1. require 'RMagick'
2. include Magick
3.
4. cat = ImageList.new("Cheetah.jpg")
5. smallcat = cat.minify
6. smallcat.display
7. exit

The difference is the statement on line 5. This statement sends the minify method to cat. The minify method is an Image method that reduces the size of an image to half its original size. Remember, since minify is an Image method, the ImageList class sends minify to the current (and only) image. The return value is a new image, half the size of the original.

The Image class has its own display method, which displays the single image on the X Window screen. Like ImageList#display, Image#display makes a picture of a (in this case, small) cheetah appear on your monitor.

Here's how to write the small cheetah to a file in GIF format.

1. require 'RMagick'
2. include Magick
3.
4. cat = ImageList.new("Cheetah.jpg")
5. smallcat = cat.minify
6. smallcat.display
7. smallcat.write("Small-Cheetah.gif")
8. exit

The statement on line 7 writes the image to a file. Notice that the filename extension is gif. When writing images, ×Magick uses the filename extension (see Image formats and filenames) to determine what image format to write. In this example, the Small-Cheetah.gif file will be in the GIF format. Notice how easy it is to covert an image from one format to another?

So why, in the previous example, did I create cat as an ImageList object containing just one image, instead of creating an Image object? No reason, really. When you only have one image to deal with, imagelists and images are pretty much interchangeable.

Note: In most cases, an Image method does not modify the image to which it is sent. Instead, the method returns a new image, suitably modified. For example, the resize method returns a new image, sized as specified. The receiver image is unaltered. (Following the Ruby convention, when a method alters the receiver object, the method name ends with "!". For example, the resize! method resizes the receiver in place.)

Reading, writing, and creating images

You've already seen that you can create an imagelist and initialize it by specifying the name of an image file as the argument to ImageList.new. In fact, new can take any number of file name arguments. If the file contains a single image, new reads the file, creates an image, and adds it to the imagelist. If the file is a multi-frame image file, new adds an image for each frame or layer in the file. Lastly, new changes the scene number to point to the last image in the imagelist. In the simple case, new reads a single image from a file and sets the scene number to 0.

Underneath the covers, new calls the Image class's read method to read the image file. The read method is a class method. Given one or more file names, read reads the files and constructs a Image object for each image in the files. The return value is an array of one or more images. Upon return, new simply appends the new images to the imagelist.

You can also create an Image from scratch by calling Image.new. This method takes 2 or 3 arguments. The first argument is the number of columns in the new image (its width). The second argument is the number of rows (its height). If present, the 3rd argument is a Fill object. To add a "scratch" image to an imagelist, call ImageList#new_image. This method calls Image.new, adds the new image to the imagelist, and sets the scene number to point to the new image. Scratch images are good for drawing on or creating images by compositing.

Like many other methods in the Image and ImageList classes, Image.new accepts an optional block that can be used to set additional optional parameters. If the block is present, Image.new creates a parameter object and yields to the block in the scope of that object. You set the parameters by calling attribute setter methods defined in the parameter object's class. For example, you can set the background color of a new image to red with the background_color= method, as shown here:

require 'RMagick'
include Magick
# Create a 100x100 red image.
f = Image.new(100,100) { self.background_color = "red" }
f.display
exit

Within the parameter block you must use self so that Ruby can knows that this statement is a method call, not an assignment to a variable.

Similar to Image.new, ImageList#new_image also accepts an optional block, passing it on to Image.new.

You can create an image by capturing it from the XWindow screen using Image.capture. This method can capture the root window, a window identified by name or ID number, or perform an interactive capture whereby you designate the desired window by clicking it or by drawing a rectangle on the screen with your mouse.

Both the Image class and the ImageList class have write methods. Both accept a single argument, the name of the file to be written. Image#write simply writes the image to a file. Like the Image#read method, write yields to an optional block that you can use to set parameters that control how the image is written.

If an ImageList object contains only one image, then ImageList#write is the same as Image#write. However, if the imagelist contains multiple images and the file format (determined by the file name extension, as I mentioned earlier) supports multi-frame images, Image#write will automatically create a multi-frame image file.

For example, the following program reads three GIF files and then uses ImageList#write to combine all the images in those files (remember, each input file can contain multiple images) into one animated GIF file.

#! /usr/local/bin/ruby -w
require 'RMagick'
anim = ImageList.new("start.gif", "middle.gif", "finish.gif")
anim.write("animated.gif")
exit

Displaying images

RMagick defines 3 methods for displaying images and imagelists. Both the Image class and the ImageList class have a display method. The Image#display method displays the image on the default X Window screen. For imagelists with just one image, ImageList#display is identical to Image#display. However, if the imagelist contains multiple images, ImageList#display displays each of the images in turn. With both methods, right-clicking the display window will produce a menu of other options.

The ImageList#animate method repeatedly cycles through all the images in an imagelist, displaying each one in turn. You can control the speed of the animation with the ImageList#delay= method.

Examining and modifying images

Once you've created an image or imagelist, what can you do with it? The Image and ImageList classes define over 100 methods for examining and modifying images, both individually and in groups. Remember, unless the ImageList class defines a method with the same name, you can send any method defined in the Image class to an instance of the ImageList class. The ImageList class sends the method to the current image and returns the result.

The methods can be classified into the following broad groups.1 ImageList methods are shown in blue.

Utility methods
<=> Compare images
<=> Compare imagelists
[] Reference an image property
[]= Set an image property
changed? Has the image been changed?
copy Deep copy the image
copy Deep copy the imagelist
difference Compute the difference between two images
export_pixels (5.5.7) Extract pixel data into an array
get_pixels Copy a region of pixels from the image
gray? Are all pixels gray?
monochrome? Are all pixels black or white?
opaque? Are all pixels opaque?
palette? Is the image PseudoClass type and does it have 256 colors or less?
properties Return all image properties
signature Compute the image's 64-byte message digest
strip! (5.5.8) Strips an image of all comments and profiles
Methods to reduce the number of colors in an image or group of images
compress_colormap! Remove duplicate or unused entries in the colormap
map Replace the colors of an image with the closest color from a reference image
map Replace the colors of all the images in an imagelist with the closest color from a reference image
ordered_dither Reduce color images to monochrome using the ordered dithering technique
quantize Analyze the colors within an image and choose a fixed number of colors to represent the image
quantize Analyze the colors within all the images in an imagelist and choose a fixed number of colors to represent the images
Methods to resize an image
change_geometry Change image geometry as specified by a geometry string
magnify Increase the size of an image by 2
minify Decrease the size of an image by 2
resize Change the size of an image using the specified filter
sample Change the size of an image with pixel sampling
scale Change the size of an image
thumbnail (5.5.2) Fast resize for thumbnail images
Methods to transform an image or group of images
append Append all the images in the imagelist vertically or horizontally
average Average all the images in the imagelist into a single image
chop Remove a region of an image and collapses the image to occupy the removed portion
coalesce Composite the images in the imagelist
composite Composite an image onto another image
composite_affine Composite an image onto another image as dictated by the affine transform
crop Extract a region of the image
deconstruct Compare each image with the next and returns the maximum bounding region of any pixel differences it discovers
flatten_images Merge the images in the imagelist
flip Create a vertical mirror image of the image
flop Create a horizontal mirror image of the image
mosaic Inlay the images in the imagelist into a single image
profile! Add or remove a ICM, IPTC, or generic profile from a image
roll Offset an image
shave Shave regions from the edges of the image
Methods to shear or rotate an image by an arbitrary angle
affine_transform Transform an image as dictated by an affine matrix
rotate Rotate an image by the specified angle
shear Shear an image along the X or Y axis, creating a parallelogram
Methods to enhance an image
contrast Enhance the intensity differences between the lighter and darker elements of the image
equalize Apply a histogram equalization to the image
gamma_correct Gamma-correct an image
level Adjust the levels of an image
level_channel   (5.5.3) Adjust the levels of an image
modulate Change the brightness, saturation, and hue of a image
negate Negate the colors in the image
normalize Enhance the contrast of a color image by adjusting the pixels' color to span the entire range of colors available
Methods to add effects to an image
adaptive_threshold (5.5.2) Threshold an image whose global intensity histogram doesn't contain distinctive peaks
add_noise Add random noise
black_threshold (5.5.7) Force all pixels below the threshold into black.
blur_image Blur the image
charcoal Add a charcoal effect
channel_threshold Change the value of individual pixels based on the intensity of each pixel channel
colorize Blend the fill color with each pixel in the image
convolve Apply a custom convolution kernel to the image
despeckle Reduce the speckle noise in the image
edge Find edges in the image
emboss Return a grayscale image with a three-dimensional effect
enhance Apply a digital filter that improves the quality of a noisy image
gaussian_blur Blur the image
implode Implode the pixels in the image
median_filter Applie a digital filter that improves the quality of a noisy image
morph Transform each image in the imagelist to the next in sequence by creating intermediate images
motion_blur Simulate a motion blur
oil_paint Add an oil paint effect
random_channel_threshold (5.5.7) Change the value of individual pixels based on the intensity of each pixel compared to a random threshold.
reduce_noise Smooth the contours of an image while still preserving edge information
shade Shine a distant light on an image to create a three-dimensional effect
sharpen Sharpen the image
solarize Apply a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light
spread Randomly displace each pixel in a block
stegano Hide a digital watermark within the image
stereo Combine two images and produces a single image that is the composite of a left and right image of a stereo pair
swirl Swirl the pixels about the center of the image
threshold Change the value of individual pixels based on the intensity of each pixel compared to threshold.
unsharp_mask Sharpen the image
wave Add a "ripple" effect
white_threshold (5.5.7) Force all pixels above the threshold into white.
Methods to decorate an image
border Surround the image with a border
frame Add a simulated three-dimensional border around the image
raise Create a simulated three-dimensional button-like effect by lightening and darkening the edges of the image
Methods to change the colors or opacity of an image
color_fill_to_border Change the color value of any neighbor pixel that is not the border color.
color_floodfill Change the color value of any neighbor pixel that matches the color of the target pixel
colormap Get or set the color in the colormap at the specified index
color_point Set the color of a single pixel.
color_reset! Set all the pixels in the image to the specified color.
cycle_colormap Displace an image's colormap by a given number of positions
erase! Set all the pixels in the image to the background color
matte_fill_to_border Make all neighbor pixels that are not the border color transparent
matte_floodfill Make all the neighbor pixels that are the same color as the target pixel transparent
import_pixels (5.5.7) Replace pixels in an image with pixel data from an array.
matte_point Make the target pixel transparent
matte_reset! Make all pixels transparent
opaque Change all pixels having the target color to the replacement color
pixel_color Get or set the color of a single pixel
store_pixels Replace a region of the image with an arbitrary set of pixels
texture_fill_to_border Replace the neighbor pixels that are not the border color with a texture
texture_floodfill Replace the neighbor pixels having the specified color with a texture
transparent Change the opacity value of the pixels having the specified color
Methods that don't really fit into any of the other categories
channel Extract a color channel
montage Tile image thumbnails across a canvas
segment Segment an image by analyzing the histograms of the color components and identifying units that are homogeneous with the fuzzy c-means technique
Methods to convert an image to/from a Binary Large OBject
to_blob Construct a BLOB from an image
to_blob Construct a BLOB from all the images in an imagelist
from_blob Create an image from a BLOB
from_blob Create an imagelist from one or more BLOBs

Marshaling images

Image and ImageList objects can be serialized using Ruby's Marshal module. Marshaling is supported via ×Magick's Binary Large OBject functions ImageToBlob (for dumping) and BlobToImage (for loading).

Notes

  1. Some image formats cannot be dumped. The only way to be sure it will work is to try it.
  2. Images in lossy formats, such as JPEG, will have a different signature after being reconstituted and therefore will not compare equal (using Image#<=>) to the original image.

Drawing on and adding text to images

The Draw class is the third major class in the Magick module. This class defines two kinds of methods. The first kind are methods that support 2D vector and raster drawing on images. The second kind are methods that support writing text on an image, known as annotation.

Drawing

×Magick supports a set of 2D drawing commands that are very similar to the commands and elements defined by the W3C's Scalable Vector Graphics (SVG) 1.0 Specification. In RMagick, each command (called a primitive) is implemented as a method in the Draw class. To draw on an image, simply

  1. Create an instance of the Draw class.
  2. Call one or more primitive methods with the appropriate arguments.
  3. Invoke the draw method, specifying an image to draw on.

The primitive methods do not draw anything directly. When you call a primitive method, you are simply adding the primitive and its arguments to a list of primitives stored in the draw object. To "execute" the primitive list, call draw. Drawing the primitives does not destroy them. You can draw on another image by calling draw again, specifying a different image as the "canvas." Of course you can also draw on an image with multiple draw objects, too. The canvas can be any image or imagelist, created by reading an image file or from scratch using ImageList#new_image or Image.new. (If you pass an imagelist object to draw, it draws on the current image.)

Here's an illustration of the default drawing coordinate system. The origin is in the top left corner. The x axis extends to the right. The y axis extends downward. The units are pixels. 0° is at 3 o'clock and rotation is clockwise. The units of rotation are usually degrees.2

You can change the default coordinate system by specifying a scaling, rotation, or translation transformation.

(Click the image to see the Ruby program that created it.)

ex/axes.gif

RMagick's primitive methods include methods for drawing points, lines, Bezier curves, shapes such as ellipses and rectangles, and text. Shapes and lines have a fill color and a stroke color. Shapes are filled with the fill color unless the fill opacity is 0. Similarly, shapes are stroked with the stroke color unless the stroke opacity is 0. Text is considered a shape and is stroked and filled. Other rendering properties you can set include the stroke width, antialiasing, stroke patterns, and fill patterns. (Yes, you can even fill text with a pattern!)

As an example, here's the section of the Ruby program that created the circle in the center of the above image.

 1. !# /usr/local/bin/ruby -w
 2. require 'RMagick'
 3.
 4. canvas = Magick::ImageList.new
 5. canvas.new_image(250, 250, Magick::HatchFill.new('white', 'gray90'))
 6.
 7. circle = Magick::Draw.new
 8. circle.stroke('tomato')
 9. circle.fill_opacity(0)
10. circle.stroke_opacity(.75)
11. circle.stroke_width(6)
12. circle.stroke_linecap('round')
13. circle.stroke_linejoin('round')
14. circle.ellipse(canvas.rows/2,canvas.columns/2, 80, 80, 0, 315)
15. circle.polyline(180,70, 173,78, 190,78, 191,62)
16. circle.draw(canvas)

The statements on lines 4 and 5 create the drawing canvas with a single 250x250 image. The HatchFill object fills the image with light-gray lines 10 pixels apart. The statement on line 7 creates a Draw object. The method calls on lines 8-15 construct a list of primitives that are "executed" by the draw method call on line 16.

The stroke method sets the stroke color, as seen on line 8. Normally, shapes are filled, but the call to fill_opacity on line 9 sets the opacity to 0, so the background will show through the circle. The tomato-colored stroke line itself is set slightly transparent by the call to stroke_opacity on line 10. The method calls on lines 11 through 13 set the stroke width and specify the appearance of the line ends and corners.

The ellipse method call on line 14 describes an circle in the center of the canvas with a radius of 80 pixels. The ellipse occupies 315° of a circle, starting at 0° (that is, 3 o'clock). The polyline call on line 15 adds the arrowhead to the circle. The arguments (always an even number) are the x- and y-coordinates of the points the line passes through.

Finally, the draw method on line 16 identifies the canvas to be drawn on and executes the stored primitives.

Annotation

The Draw#annotate method draws text on an image. In its simplest form, annotate requires only arguments that describe where to draw the text and the text string.

Most of the time, you'll want to specify text properties such as the font, its size, font styles such as italic, font weights such as bold, the fill and stroke color, etc. The Draw class defines attribute writers for this purpose. You can set the desired text properties by calling the attribute writers before calling annotate, or you can call them in an image block associated with the annotate call.

The following example shows how to use annotate to produce this image.

ex/rubyname.rb
 1.   #! /usr/local/bin/ruby -w
 2.   require 'RMagick'
 3.
 4.   # Demonstrate the annotate method
 5.
 6.   Text = 'RMagick'
 7.
 8.   granite = Magick::ImageList.new('granite:')
 9.   canvas = Magick::ImageList.new
10.   canvas.new_image(300, 100, Magick::TextureFill.new(granite))
11.
12.   text = Magick::Draw.new
13.   text.font_family = 'helvetica'
14.   text.pointsize = 52
15.   text.gravity = Magick::CenterGravity
16.
17.   text.annotate(canvas, 0,0,2,2, Text) {
18.      self.fill = 'gray83'
19.   }
20.
21.   text.annotate(canvas, 0,0,-1.5,-1.5, Text) {
22.      self.fill = 'gray40'
23.   }
24.
25.   text.annotate(canvas, 0,0,0,0, Text) {
26.      self.fill = 'darkred'
27.   }
28.
29.   canvas.write('rubyname.gif')
30.   exit

This program uses three calls to annotate to produce the "etched" appearance. All three calls have some parameters in common but the fill color and location are different.

First, the statements in lines 8-10 create the background. See class Fill for information about the TextureFill class. The "granite:" image format is one of ×Magick's built-in image formats. See "Built-in image formats" for more information. The statement on line 12 creates the Draw object that does the annotation. The next 3 lines set the values of the attributes that are common to all 3 annotate calls.

The first annotate argument is the image on which the text will be drawn. Arguments 2-5, width, height, x, and y, describe a rectangle about which the text is drawn. This rectangle, combined with the value of gravity, define the position of the text. When the gravity value is CenterGravity the values of width and height are unused.

The first call to annotate, on lines 17-19, draws the text 2 pixels to the right and down from the center. The self.fill = 'gray83' statement sets the text color to light gray. The second call to annotate, on lines 21-22, draws dark gray text 1.5 pixels to the left and up from the center. The last call, on lines 25-27, draws the text a third time, in dark red, exactly in the center of the image.

Where to go from here

The next section, "ImageMagick/GraphicsMagick Conventions," describes some conventions that you need to know, such as how ×Magick determines the graphic format of an image file, etc. The ×Magick (www.imagemagick.org) and GraphicsMagick (www.graphicsmagick.org) web sites (from which much of the information in these pages has been taken) offers a lot of detail about ×Magick. While the ×Magick web site doesn't describe RMagick, you can often use the documentation to learn more about a RMagick method by reading about the ×Magick functions the method calls. (In the Reference section of this document, most of the method descriptions include the name of the ×Magick function that the method calls.) Check out the example programs. Almost every one of the RMagick methods is demonstrated in one of the examples.

Good luck!


Footnotes

1Most of the content in this table is taken from the ×Magick documentation.

2The rotation attributes rx and ry in the AffineMatrix class use radians instead of degrees.