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
1. require 'RMagick' 2. include Magick 3. 4. cat = ImageList.new("Cheetah.jpg") 5. cat.display 6. 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 2 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 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.
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 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.
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 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.)
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' 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 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.
#! /usr/local/bin/ruby -w require 'RMagick' anim = ImageList.new("start.gif", "middle.gif", "finish.gif") anim.write("animated.gif") exit
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.
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 ×Magick. See the method documentation for details.
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).
The Draw class is the third major class in the Magick module. This class defines two kinds of methods, drawing methods and annotation methods.
×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.1 Specification. In RMagick, each
command (called a primitive) is implemented as a method
in the Draw
class. To draw on an image, simply
Draw
class.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.)
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.3
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.
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(0.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 (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.
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.
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
Fill classes
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.
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 ImageMagick (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 these web sites don'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!
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.
2If you installed RMagick using Rubygems you must set up the RubyGems environment before using RMagick. You can do one of
require 'rubygems'
statement to your
programrubygems
to the RUBYOPT environment
variableSee the RubyGems doc for more information.
3The rotation
attributes rx
and ry
in the AffineMatrix
class
use radians instead of degrees.