Adding Text to an Image

Credit: Antonio Cangiano

Problem

You want to add some text to an imageperhaps a caption or a copyright statement.

Solution

Create an RMagick Draw object and call its annotate method, passing in your image and the text.

The following code adds the copyright string © NPS to the bottom-right corner of the canyon.png image. It also specifies the font, the text color and size, and other features of the text:

require ubygems require RMagick img = Magick::Image.read(canyon.png).first my_text = "251 NPS" copyright = Magick::Draw.new copyright.annotate(img, 0, 0, 3, 18, my_text) do self.font = Helvetica self.pointsize = 12 self.font_weight = Magick::BoldWeight self.fill = white self.gravity = Magick::SouthEastGravity end img.write( canyoncopyrighted.png)

The resulting image looks like Figure 12-1.

Figure 12-1. With a copyright message in the bottom-right corner

Discussion

The annotate method takes a code block that sets properties on the Magick::Draw object, describing how the annotation should be done. You can also set the properties on the Draw object before calling annotate. This code works the same as the code given in the Solution:

require ubygems require RMagick img = Magick::Image.read("canyon.png").first my_ text = \251 NPS copyright = Magick::Draw.new copyright.font = Helvetica copyright.pointsize = 12 copyright.font_weight = Magick::BoldWeight copyright.fill = white copyright.gravity = Magick::SouthEastGravity copyright.annotate(img, 0, 0, 3, 18, my_text) img.write(canyoncopyrighted.png)

What do these attributes do?

Draw#annotate itself takes six arguments:

In the Solution I wrote:

copyright.annotate(img, 0, 0, 3, 15, my_text)

The width and height are zeros, which indicates that annotate should use the whole image as its annotation rectangle. Earlier I gave the Draw object a gravity attribute of SouthEastGravity. This means that annotate will position the text at the bottom-right corner of the rectangle: that is, at the bottom-right corner of the image itself. The offsets of 3 and 18 indicate that the text should start vertically 18 pixels from the bottom of the box, and end horizontally 3 pixels from the right border of the box.

To position the text in the center of the image, I just change the gravity:

copyright.gravity = Magick::CenterGravity copyright.annotate(img, 0, 0, 0, 0, my_text)

Note that I didn have to specify any offsets: CenterGravity orients the text to be is in the exact center of the image (Figure 12-2). Specifying offsets would only move the text off-center.

The Magick library does substitutions for various special characters: for instance, the string "%t" will be replaced with the filename of the image. For more information about special characters, GravityType constants, and other annotate attributes that can let you fully customize the text appearance, refer to the RMagick documentation.

Figure 12-2. With a copyright message in the center of the image

See Also

Категории