JavaScript EditorFreeware JavaScript Editor     Perl Tutorials 

Main Page Previous Section Next Section

Recipe 15.20 Adding Text to an Image

15.20.1 Problem

You want to write text onto an existing image. For example, you want to add a small copyright message to all photos on your web site.

15.20.2 Solution

Use the GD module from CPAN:

use GD;
$image = GD::Image->new($FILENAME);
$blue = $image->colorAllocate(0,0,255);
$image->string(gdTinyFont, 10, 10, "Copyright Me, 2037", $blue);
# write $image->png( ) to file

15.20.3 Discussion

The GD module can load only certain file formats; precisely which depends on the C libraries available when the underlying C library of GD was built. At the time of this writing, GD could read and write PNG, JPEG, XBM, XPM, and WBMP (Windows Bitmap), as well as its own GD2 and GD formats.

The arguments to the string method are: the font to use, the x and y coordinates to draw at, the string to draw, and the color to draw the text in.

GD comes with five fonts: gdTinyFont, gdSmallFont, gdMediumBoldFont, gdLargeFont, and gdGiantFont. If your GD was compiled to handle TrueType fonts, you can write with a TrueType font using:

$image->stringFT($color, $font, $point_size, $angle, $x, $y, $string);

Here, $font is the absolute pathname of the .ttf file containing the TrueType font. The $point_size and $angle parameters indicate the size (in points; fractions are acceptable) and rotation from horizontal (in radians). For example:

$image->stringFT($blue, '/Users/gnat/fonts/arial.ttf', 8, 0,
                 10, 20, 'Copyright Me Me Me');

15.20.4 See Also

The documentation for the GD module; Perl Graphics Programming

    Main Page Previous Section Next Section

    JavaScript EditorJavaScript Verifier     Perl Tutorials