O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.2. Adding Text to an Image

Credit: Antonio Cangiano

Problem

You want to add some text to an image—perhaps 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 'rubygems'
	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.

With a copyright message in the bottom-right corner

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 'rubygems'
	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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required