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 displays1 it on your monitor

require "rmagick"

cat = Magick::ImageList.new("Cheetah.jpg")
cat.display
exit

MS Windows users note: The display method does not work on native MS Windows. You must use an external viewer to view the images you create.

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 Concepts - 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 the object. 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.

The Image and ImageList classes are closely related. 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 by specifying its dimensions. 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 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. The ImageList class includes methods that 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 an image to the list.

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

require "rmagick"

cat = Magick::ImageList.new("Cheetah.jpg")
smallcat = cat.minify
smallcat.display
exit

The difference is the statement on line 5. This statement sends the minify method to the imagelist. 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.

Line 6 demonstrates the Image class's display method, which displays a single image on the X Window screen. 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.

require "rmagick"

cat = Magick::ImageList.new("Cheetah.jpg")
smallcat = cat.minify
smallcat.display
smallcat.write("Small-Cheetah.gif")
exit

The statement on line 7 writes the image to a file. Notice that the filename extension is gif. When writing images, ImageMagick uses the filename extension 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? (For more details, see Image formats and filenames.)

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.

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"

# Create a 100x100 red image.
f = Magick::Image.new(100,100) { |options| options.background_color = "red" }
f.display
exit

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

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.

require "rmagick"

anim = Magick::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. ImageList method descriptions look like this. Some of the listed methods are not available in some releases of ImageMagick. See the method documentation for details.

Utility methods

<=>
Compare 2 images
<=>
Compare 2 imagelists
[ ]
Reference an image property
[ ]=
Set an image property
add_profile
Add an ICC, IPTC, or generic profile
changed?
Has the image been changed?
channel
Extract a color channel from the image
compare_channel
Compare one or more channels between two images
channel_depth
Return the depth of the specified channel or channels
channel_extrema
Return the maximum and minimum intensity values for one or more channels in the image
check_destroyed
Raise an exception if the image has been destroyed
clone
Return a shallow copy of the image
clone
Return a shallow copy of the imagelist
color_histogram
Count the number of times each unique color appears in the image
combine
Combines the grayscale value of the pixels in each image to form a new image.
copy
Return a deep copy of the image
copy
Return a deep copy of the imagelist
delete_profile
Delete an ICC, IPTC, or generic profile
destroy!
Return all memory associated with the image to the system
destroyed?
Has the image has been destroyed?
difference
Compute the difference between two images
distortion_channel
Compare one or more channels to a reconstructed image
dup
Return a shallow copy of the image
dup
Return a shallow copy of the imagelist
each_pixel
Iterate over all the pixels in the image
each_profile
Iterate over all the profiles associated with the image
export_pixels
Extract pixel data from the image into an array
export_pixels_to_str
Extract pixel data from the image into a string
find_similar_region
Search for a rectangle matching the target
get_exif_by_entry, get_exif_by_number
Get one or more EXIF property values for the image
get_pixels
Copy a region of pixels from the image
gray?
Are all the pixels in the image gray?
histogram?
Does the image have <= 1024 unique colors??
import_pixels
Replace pixels in the image with pixel data from an array
monochrome?
Are all the pixels in the image either black or white?
opaque?
Are all the pixels in the image opaque?
palette?
Is the image a PseudoClass type image with 256 colors or less?
preview
Show the effect of a transformation method on the image
profile!
Add or remove an ICM, IPTC, or generic profile from the image
properties
Iterate over all the properties associated with the image
separate
Construct a grayscale image for each channel specified
set_channel_depth
Set the specified channel's depth
signature
Compute the 64-byte message signature for the image
store_pixels
Replace a region of pixels in the image
strip!
Strip the image of all comments and profiles
sync_profiles
Synchronize the image properties with the image profiles
unique_colors
Construct an image from the unique colors
view
Access pixels by their coordinates.

Reduce the number of colors

compress_colormap!
Remove duplicate or unused entries in the image's colormap
ordered_dither
Dither the image to a predefined pattern
posterize
Reduce the number of colors for a "poster" effect
quantize
Choose a fixed number of colors to represent the image
quantize
Choose a fixed number of colors to represent all the images in the imagelist
remap
Change the colors in the image to the colors in a reference image.
remap
Change the images in the imagelist to use a common color map.

Resize

change_geometry
Compute a new constrained size for the image
liquid_rescale
Rescale image with seam-carving
magnify
Double the size of the image
minify
Halve the size of the image
resample
Resample the image to the specified horizontal and vertical resolution
resize
Resize the image using a filter
resize_to_fill
Resize and crop while retaining the aspect ratio
resize_to_fit
Resize the image retaining the aspect ratio
sample
Resize the image using pixel sampling
scale
Resize the image
thumbnail
Quickly create a thumbnail of the image

Change colors or opacity

color_fill_to_border
Change the color of neighboring pixels. Stop at the image's border color.
color_floodfill
Change the color of neighboring pixels that are the same color
colormap
Get or set a color in the image's colormap
color_point
Change the color of a single pixel in the image
color_reset!
Set the entire image to a single color
cycle_colormap
Displace the image's colormap
erase!
Set the entire image to a single color
matte_fill_to_border
Make transparent neighboring pixels. Stop at the image's border color.
matte_floodfill
Make transparent neighboring pixels that are the same color
matte_point
Make a single pixel transparent
matte_reset!
Make the entire image transparent
opaque, opaque_channel
Change all pixels from the specified color to a new color
pixel_color
Get or set the color of a single pixel
splice
Splice a solid color into the image.
texture_fill_to_border
Replace neighbor pixels with pixels from a texture image. Stop at the image's border color.
texture_floodfill
Replace neighboring pixels that are the same color with pixels from a texture image
paint_transparent, transparent
Change the opacity value of pixels having the specified color
transparent_chroma
Change the opacity value of pixels within the specified range

Rotate, flip, or shear

affine_transform
Transform the image as dictated by an affine matrix
auto_orient
Rotate or flip the image using the EXIF orientation tag
deskew
Straighten the image
flip
Create a vertical mirror image
flop
Create a horizontal mirror image
rotate
Rotate the image by the specified angle
shear
Shear the image along the X or Y axis, creating a parallelogram
transpose
Create a horizontal mirror image
transverse
Create a vertical mirror image

Composite

add_compose_mask
Add a mask to the background image in a composite operation
average
Average all the images in the imagelist into a single image
blend
Blend two images together
composite
Composite a source image onto the image
composite_affine
Composite a source image onto the image as dictated by an affine matrix
composite_layers
Composite two imagelists
composite_mathematics
Merge a source image onto the image according to a formula.
composite_tiled
Composite multiple copies of an image over another image
delete_compose_mask
Delete a compose mask
displace
Distort the image using a displacement map
dissolve
Dissolve two images into each other
extent
Extend or crop the image over the background color.
watermark
Composite a watermark onto the image

Transform

append
Append all the images in the imagelist into a single image
chop
Chop a region from the image
coalesce
Merge successive images in the imagelist into a new imagelist
crop
Extract a region from the image
decipher
Convert enciphered pixels to plain pixels
deconstruct
Construct a new imagelist containing images that include only the changed pixels between each image and its successor
distort
Distort the image
encipher
Encipher plain pixels
excerpt
Excerpt a rectangle from the image
flatten_images
Merge all the images in the imagelist into a single image
mosaic
Inlay all the images in the imagelist into a single image
optimize_layers
Optimize or compare image layers
resize_to_fill
Resize and crop while retaining the aspect ratio
roll
Offset the image
shave
Shave regions from the edges of the image
trim
Remove borders from the edges of the image

Enhance

clut_channel
Replace the channel values in the image with a lookup of its replacement value in an LUT gradient image.
contrast
Enhance the intensity differences between the lighter and darker elements in the image
contrast_stretch_channel
Improve the contrast in the image by stretching the range of intensity values
despeckle
Reduce the speckle noise in the image
enhance
Apply a digital filter that improves the quality of a noisy image
equalize, equalize_channel
Apply a histogram equalization to the image
function_channel
Apply a function to selected channel values
fx
Apply a mathematical expression to an image
auto_gamma_channel, gamma_correct, gamma_channel
Gamma correct the image
auto_level_channel, level, level_channel, level_colors, levelize_channel
Adjust the levels of one or more channels in the image
linear_stretch
Stretch with saturation the image contrast
median_filter
Apply a digital filter that improves the quality of a noisy image
modulate
Change the brightness, saturation, or hue of the image
negate, negate_channel
Negate the colors of the image
normalize, normalize_channel
Enhance the contrast of the image
quantum_operator
Performs an integer arithmetic operation on selected channels values
reduce_noise
Smooth the contours of an image while still preserving edge information
adaptive_sharpen, adaptive_sharpen_channel, sharpen, sharpen_channel, unsharp_mask, unsharp_mask_channel
Sharpen the image
sigmoidal_contrast_channel
Adjusts the contrast of an image channel with a non-linear sigmoidal contrast algorithm

Add effects

adaptive_threshold
Threshold an image whose global intensity histogram doesn't contain distinctive peaks
add_noise, add_noise_channel
Add random noise
bilevel_channel
Change the value of individual image pixels based on the intensity of each pixel channel
black_threshold
Force all pixels below the threshold into black
blue_shift
Simulate a scene at nighttime in the moonlight
adaptive_blur, adaptive_blur_channel, blur_image, blur_channel, gaussian_blur, gaussian_blur_channel, motion_blur, radial_blur, radial_blur_channel, selective_blur_channel
Blur the image
colorize
Blend the fill color with each pixel in the image
convolve, convolve_channel
Apply a custom convolution kernel to the image
segment
Segment an image by analyzing the histograms of the color components and identifying units that are homogeneous with the fuzzy c-means technique
random_threshold_channel
Change the value of individual pixels based on the intensity of each pixel compared to a random threshold.
recolor
translate, scale, shear, or rotate the image colors
threshold
Change the value of individual pixels based on the intensity of each pixel compared to threshold
white_threshold
Force all pixels above the threshold into white

Add special effects

charcoal
Add a charcoal effect
edge
Find edges in the image
emboss
Add a three-dimensional effect
implode
Implode or explode the center pixels in the image
morph
Transform each image in the imagelist to the next in sequence by creating intermediate images
oil_paint
Add an oil paint effect
polaroid
Simulate a Polaroid® instant picture
sepiatone
Applies an effect similar to the effect achieved in a photo darkroom by sepia toning.
shade
Shine a distant light on an image to create a three-dimensional effect
shadow
Add a shadow to an image
sketch
Simulate a pencil sketch
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 into 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
vignette
Soften the edges of the image to create a vignette
wave
Add a ripple effect to the image
wet_floor
Create a "wet floor" reflection of the image

Decorate

border
Surround the image with a solid-colored 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

Create thumbnail montages

montage
Tile image thumbnails across a canvas

Create image blobs

from_blob
Create an image from a BLOB
from_blob
Create an imagelist from one or more BLOBs
to_blob
Construct a BLOB from an image
to_blob
Construct a BLOB from all the images in the imagelist

Marshaling images

ImageList, Image, Draw, and Pixel objects are marshaled using custom serialization methods. Images are marshaled with ImageMagick'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 <=>) to the original image.
  3. Image metadata may be changed by marshaling.

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, drawing methods and annotation methods.

Drawing

ImageMagick 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.1 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. Call the draw method.

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.)

Drawing coordinate system

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.)

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.

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

require "rmagick"

canvas = Magick::ImageList.new
canvas.new_image(250, 250, Magick::HatchFill.new('white', 'gray90'))

circle = Magick::Draw.new
circle.stroke('tomato')
circle.fill_opacity(0)
circle.stroke_opacity(0.75)
circle.stroke_width(6)
circle.stroke_linecap('round')
circle.stroke_linejoin('round')
circle.ellipse(canvas.rows/2,canvas.columns/2, 80, 80, 0, 315)
circle.polyline(180,70, 173,78, 190,78, 191,62)
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 (opacity = 1.0), but the call to fill_opacity on line 9 sets the opacity to 0, so the background will show through the circle. Similarly, the stroke lines are normally opaque, but the tomato-colored stroke line in this example is made 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 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.

annotate example
require "rmagick"

# Demonstrate the annotate method

Text = 'RMagick'

granite = Magick::ImageList.new('granite:')
canvas = Magick::ImageList.new
canvas.new_image(300, 100, Magick::TextureFill.new(granite))

text = Magick::Draw.new
text.font_family = 'helvetica'
text.pointsize = 52
text.gravity = Magick::CenterGravity

text.annotate(canvas, 0,0,2,2, Text) { |options|
  options.fill = 'gray83'
}

text.annotate(canvas, 0,0,-1.5,-1.5, Text) { |options|
  options.fill = 'gray40'
}

text.annotate(canvas, 0,0,0,0, Text) { |options|
  options.fill = 'darkred'
}

canvas.write('rubyname.gif')
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 Fill classes for information about the TextureFill class. The "granite:" image format is one of ImageMagick'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 options.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 Conventions," describes some conventions that you need to know, such as how ImageMagick determines the graphic format of an image file, etc. The ImageMagick (www.imagemagick.org) web site (from which much of the information in these pages has been taken) offers a lot of detail about ImageMagick. While this web sites doesn't describe RMagick, you can often use the documentation to learn more about a RMagick method by reading about the Magick API the method calls. (In the Reference section of this document, most of the method descriptions include the name of the Magick API that the method calls.) Check out the example programs. Almost every one of the methods is demonstrated in one of the examples.

Good luck!

Footnotes

1The display and animate methods do not work on MS Windows. You will have to write the image to a file and view it with a separate image viewer.

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