1GD(3) User Contributed Perl Documentation GD(3)
2
3
4
6 GD.pm - Interface to Gd Graphics Library
7
9 use GD;
10
11 # create a new image
12 $im = new GD::Image(100,100);
13
14 # allocate some colors
15 $white = $im->colorAllocate(255,255,255);
16 $black = $im->colorAllocate(0,0,0);
17 $red = $im->colorAllocate(255,0,0);
18 $blue = $im->colorAllocate(0,0,255);
19
20 # make the background transparent and interlaced
21 $im->transparent($white);
22 $im->interlaced('true');
23
24 # Put a black frame around the picture
25 $im->rectangle(0,0,99,99,$black);
26
27 # Draw a blue oval
28 $im->arc(50,50,95,75,0,360,$blue);
29
30 # And fill it with red
31 $im->fill(50,50,$red);
32
33 # make sure we are writing to a binary stream
34 binmode STDOUT;
35
36 # Convert the image to PNG and print it on standard output
37 print $im->png;
38
40 GD.pm is a Perl interface to Thomas Boutell's gd graphics library (ver‐
41 sion 2.01 or higher; see below). GD allows you to create color drawings
42 using a large number of graphics primitives, and emit the drawings as
43 PNG files.
44
45 GD defines the following four classes:
46
47 "GD::Image"
48 An image class, which holds the image data and accepts graphic
49 primitive method calls.
50
51 "GD::Font"
52 A font class, which holds static font information and used for
53 text rendering.
54
55 "GD::Polygon"
56 A simple polygon object, used for storing lists of vertices prior
57 to rendering a polygon into an image.
58
59 "GD::Simple"
60 A "simple" class that simplifies the GD::Image API and then adds a
61 set of object-oriented drawing methods using turtle graphics, sim‐
62 plified font handling, ability to work in polar coordinates, HSV
63 color spaces, and human-readable color names like "lightblue".
64 Please see GD::Simple for a description of these methods.
65
66 A Simple Example:
67
68 #!/usr/local/bin/perl
69
70 use GD;
71
72 # create a new image
73 $im = new GD::Image(100,100);
74
75 # allocate some colors
76 $white = $im->colorAllocate(255,255,255);
77 $black = $im->colorAllocate(0,0,0);
78 $red = $im->colorAllocate(255,0,0);
79 $blue = $im->colorAllocate(0,0,255);
80
81 # make the background transparent and interlaced
82 $im->transparent($white);
83 $im->interlaced('true');
84
85 # Put a black frame around the picture
86 $im->rectangle(0,0,99,99,$black);
87
88 # Draw a blue oval
89 $im->arc(50,50,95,75,0,360,$blue);
90
91 # And fill it with red
92 $im->fill(50,50,$red);
93
94 # make sure we are writing to a binary stream
95 binmode STDOUT;
96
97 # Convert the image to PNG and print it on standard output
98 print $im->png;
99
100 Notes:
101
102 1. To create a new, empty image, send a new() message to GD::Image,
103 passing it the width and height of the image you want to create. An
104 image object will be returned. Other class methods allow you to ini‐
105 tialize an image from a preexisting JPG, PNG, GD, GD2 or XBM file.
106 2. Next you will ordinarily add colors to the image's color table. col‐
107 ors are added using a colorAllocate() method call. The three parame‐
108 ters in each call are the red, green and blue (rgb) triples for the
109 desired color. The method returns the index of that color in the
110 image's color table. You should store these indexes for later use.
111 3. Now you can do some drawing! The various graphics primitives are
112 described below. In this example, we do some text drawing, create an
113 oval, and create and draw a polygon.
114 4. Polygons are created with a new() message to GD::Polygon. You can
115 add points to the returned polygon one at a time using the addPt()
116 method. The polygon can then be passed to an image for rendering.
117 5. When you're done drawing, you can convert the image into PNG format
118 by sending it a png() message. It will return a (potentially large)
119 scalar value containing the binary data for the image. Ordinarily you
120 will print it out at this point or write it to a file. To ensure
121 portability to platforms that differentiate between text and binary
122 files, be sure to call "binmode()" on the file you are writing the
123 image to.
124
126 The following class methods allow you to create new GD::Image objects.
127
128 $image = GD::Image->new([$width,$height],[$truecolor])
129 $image = GD::Image->new(*FILEHANDLE)
130 $image = GD::Image->new($filename)
131 $image = GD::Image->new($data)
132 The new() method is the main constructor for the GD::Image class.
133 Called with two integer arguments, it creates a new blank image of
134 the specified width and height. For example:
135
136 $myImage = new GD::Image(100,100) ⎪⎪ die;
137
138 This will create an image that is 100 x 100 pixels wide. If you
139 don't specify the dimensions, a default of 64 x 64 will be chosen.
140
141 The optional third argument, $truecolor, tells new() to create a
142 truecolor GD::Image object. Truecolor images have 24 bits of color
143 data (eight bits each in the red, green and blue channels respec‐
144 tively), allowing for precise photograph-quality color usage. If
145 not specified, the image will use an 8-bit palette for compatibil‐
146 ity with older versions of libgd.
147
148 Alternatively, you may create a GD::Image object based on an exist‐
149 ing image by providing an open filehandle, a filename, or the image
150 data itself. The image formats automatically recognized and
151 accepted are: PNG, JPEG, XPM and GD2. Other formats, including
152 WBMP, and GD version 1, cannot be recognized automatically at this
153 time.
154
155 If something goes wrong (e.g. insufficient memory), this call will
156 return undef.
157
158 $image = GD::Image->trueColor([0,1])
159 For backwards compatibility with scripts previous versions of GD,
160 new images created from scratch (width, height) are palette based
161 by default. To change this default to create true color images
162 use:
163
164 GD::Image->trueColor(1);
165
166 somewhere before creating new images. To switch back to palette
167 based by default, use:
168
169 GD::Image->trueColor(0);
170
171 $image = GD::Image->newPalette([$width,$height])
172 $image = GD::Image->newTrueColor([$width,$height])
173 The newPalette() and newTrueColor() methods can be used to explic‐
174 itly create an palette based or true color image regardless of the
175 current setting of trueColor().
176
177 $image = GD::Image->newFromPng($file, [$truecolor])
178 $image = GD::Image->newFromPngData($data, [$truecolor])
179 The newFromPng() method will create an image from a PNG file read
180 in through the provided filehandle or file path. The filehandle
181 must previously have been opened on a valid PNG file or pipe. If
182 successful, this call will return an initialized image which you
183 can then manipulate as you please. If it fails, which usually hap‐
184 pens if the thing at the other end of the filehandle is not a valid
185 PNG file, the call returns undef. Notice that the call doesn't
186 automatically close the filehandle for you. But it does call "bin‐
187 mode(FILEHANDLE)" for you, on platforms where this matters.
188
189 You may use any of the following as the argument:
190
191 1) a simple filehandle, such as STDIN
192 2) a filehandle glob, such as *PNG
193 3) a reference to a glob, such as \*PNG
194 4) an IO::Handle object
195 5) the pathname of a file
196
197 In the latter case, newFromPng() will attempt to open the file for
198 you and read the PNG information from it.
199
200 Example1:
201
202 open (PNG,"barnswallow.png") ⎪⎪ die;
203 $myImage = newFromPng GD::Image(\*PNG) ⎪⎪ die;
204 close PNG;
205
206 Example2:
207 $myImage = newFromPng GD::Image('barnswallow.png');
208
209 To get information about the size and color usage of the informa‐
210 tion, you can call the image query methods described below. Images
211 created by reading PNG images will be truecolor if the image file
212 itself is truecolor. To force the image to be palette-based, pass a
213 value of 0 in the optional $truecolor argument.
214
215 The newFromPngData() method will create a new GD::Image initialized
216 with the PNG format data contained in $data.
217
218 $image = GD::Image->newFromJpeg($file, [$truecolor])
219 $image = GD::Image->newFromJpegData($data, [$truecolor])
220 These methods will create an image from a JPEG file. They work
221 just like newFromPng() and newFromPngData(), and will accept the
222 same filehandle and pathname arguments.
223
224 Images created by reading JPEG images will always be truecolor. To
225 force the image to be palette-based, pass a value of 0 in the
226 optional $truecolor argument.
227
228 $image = GD::Image->newFromGif($file)
229 $image = GD::Image->newFromGifData($data)
230 These methods will create an image from a GIF file. They work just
231 like newFromPng() and newFromPngData(), and will accept the same
232 filehandle and pathname arguments.
233
234 Images created from GIFs are always 8-bit palette images. To con‐
235 vert to truecolor, you must create a truecolor image and then per‐
236 form a copy.
237
238 $image = GD::Image->newFromXbm($file)
239 This works in exactly the same way as "newFromPng", but reads the
240 contents of an X Bitmap (black & white) file:
241
242 open (XBM,"coredump.xbm") ⎪⎪ die;
243 $myImage = newFromXbm GD::Image(\*XBM) ⎪⎪ die;
244 close XBM;
245
246 There is no newFromXbmData() function, because there is no corre‐
247 sponding function in the gd library.
248
249 $image = GD::Image->newFromGd($file)
250 $image = GD::Image->newFromGdData($data)
251 These methods initialize a GD::Image from a Gd file, filehandle, or
252 data. Gd is Tom Boutell's disk-based storage format, intended for
253 the rare case when you need to read and write the image to disk
254 quickly. It's not intended for regular use, because, unlike PNG or
255 JPEG, no image compression is performed and these files can become
256 BIG.
257
258 $myImage = newFromGd GD::Image("godzilla.gd") ⎪⎪ die;
259 close GDF;
260
261 $image = GD::Image->newFromGd2($file)
262 $image = GD::Image->newFromGd2Data($data)
263 This works in exactly the same way as "newFromGd()" and
264 newFromGdData, but use the new compressed GD2 image format.
265
266 $image = GD::Image->newFromGd2Part($file,srcX,srcY,width,height)
267 This class method allows you to read in just a portion of a GD2
268 image file. In addition to a filehandle, it accepts the top-left
269 corner and dimensions (width,height) of the region of the image to
270 read. For example:
271
272 open (GDF,"godzilla.gd2") ⎪⎪ die;
273 $myImage = GD::Image->newFromGd2Part(\*GDF,10,20,100,100) ⎪⎪ die;
274 close GDF;
275
276 This reads a 100x100 square portion of the image starting from
277 position (10,20).
278
279 $image = GD::Image->newFromXpm($filename)
280 This creates a new GD::Image object starting from a filename. This
281 is unlike the other newFrom() functions because it does not take a
282 filehandle. This difference comes from an inconsistency in the
283 underlying gd library.
284
285 $myImage = newFromXpm GD::Image('earth.xpm') ⎪⎪ die;
286
287 This function is only available if libgd was compiled with XPM sup‐
288 port.
289
290 NOTE: The libgd library is unable to read certain XPM files,
291 returning an all-black image instead.
292
294 Once a GD::Image object is created, you can draw with it, copy it, and
295 merge two images. When you are finished manipulating the object, you
296 can convert it into a standard image file format to output or save to a
297 file.
298
299 Image Data Output Methods
300
301 The following methods convert the internal drawing format into standard
302 output file formats.
303
304 $pngdata = $image->png([$compression_level])
305 This returns the image data in PNG format. You can then print it,
306 pipe it to a display program, or write it to a file. Example:
307
308 $png_data = $myImage->png;
309 open (DISPLAY,"⎪ display -") ⎪⎪ die;
310 binmode DISPLAY;
311 print DISPLAY $png_data;
312 close DISPLAY;
313
314 Note the use of "binmode()". This is crucial for portability to
315 DOSish platforms.
316
317 The optional $compression_level argument controls the amount of
318 compression to apply to the output PNG image. Values range from
319 0-9, where 0 means no compression (largest files, highest quality)
320 and 9 means maximum compression (smallest files, worst quality). A
321 compression level of -1 uses the default compression level selected
322 when zlib was compiled on your system, and is the same as calling
323 png() with no argument. Be careful not to confuse this argument
324 with the jpeg() quality argument, which ranges from 0-100 and has
325 the opposite meaning from compression (higher numbers give higher
326 quality).
327
328 $gifdata = $image->gifanimbegin([$GlobalCM [, $Loops]])
329 For libgd version 2.0.33 and higher, this call begins an animated
330 GIF by returning the data that comprises animated gif image file
331 header. After you call this method, call gifanimadd() one or more
332 times to add the frames of the image. Then call gifanimend(). Each
333 frame must be the same width and height.
334
335 A typical sequence will look like this:
336
337 my $gifdata = $image->gifanimbegin;
338 $gifdata .= $image->gifanimadd; # first frame
339 for (1..100) {
340 # make a frame of right size
341 my $frame = GD::Image->new($image->getBounds);
342 add_frame_data($frame); # add the data for this frame
343 $gifdata .= $frame->gifanimadd; # add frame
344 }
345 $gifdata .= $image->gifanimend; # finish the animated GIF
346 print $gifdata; # write animated gif to STDOUT
347
348 If you do not wish to store the data in memory, you can print it to
349 stdout or a file.
350
351 The image that you call gifanimbegin on is used to set the image
352 size, color resolution and color map. If argument $GlobalCM is 1,
353 the image color map becomes the GIF89a global color map. If $Loops
354 is given and >= 0, the NETSCAPE2.0 application extension is cre‐
355 ated, with looping count. Looping count 0 means forever.
356
357 $gifdata = $image->gifanimadd([$LocalCM [, $LeftOfs [, $TopOfs [,
358 $Delay [, $Disposal [, $previm]]]]]])
359 Returns the data that comprises one animated gif image frame. You
360 can then print it, pipe it to a display program, or write it to a
361 file. With $LeftOfs and $TopOfs you can place this frame in dif‐
362 ferent offset than (0,0) inside the image screen. Delay between
363 the previous frame and this frame is in 1/100s units. Disposal is
364 usually and by default 1. Compression is activated by giving the
365 previous image as a parameter. This function then compares the
366 images and only writes the changed pixels to the new frame in ani‐
367 mation. The Disposal parameter for optimized animations must be
368 set to 1, also for the first frame. $LeftOfs and $TopOfs parame‐
369 ters are ignored for optimized frames.
370
371 $gifdata = $image->gifanimend()
372 Returns the data for end segment of animated gif file. It always
373 returns string ';'. This string must be printed to an animated gif
374 file after all image frames to properly terminate it according to
375 GIF file syntax. Image object is not used at all in this method.
376
377 $jpegdata = $image->jpeg([$quality])
378 This returns the image data in JPEG format. You can then print it,
379 pipe it to a display program, or write it to a file. You may pass
380 an optional quality score to jpeg() in order to control the JPEG
381 quality. This should be an integer between 0 and 100. Higher
382 quality scores give larger files and better image quality. If you
383 don't specify the quality, jpeg() will choose a good default.
384
385 $gifdata = $image->gif().
386 This returns the image data in GIF format. You can then print it,
387 pipe it to a display program, or write it to a file.
388
389 $gddata = $image->gd
390 This returns the image data in GD format. You can then print it,
391 pipe it to a display program, or write it to a file. Example:
392
393 binmode MYOUTFILE;
394 print MYOUTFILE $myImage->gd;
395
396 $gd2data = $image->gd2
397 Same as gd(), except that it returns the data in compressed GD2
398 format.
399
400 $wbmpdata = $image->wbmp([$foreground])
401 This returns the image data in WBMP format, which is a black-and-
402 white image format. Provide the index of the color to become the
403 foreground color. All other pixels will be considered background.
404
405 Color Control
406
407 These methods allow you to control and manipulate the GD::Image color
408 table.
409
410 $index = $image->colorAllocate(red,green,blue)
411 This allocates a color with the specified red, green and blue com‐
412 ponents and returns its index in the color table, if specified.
413 The first color allocated in this way becomes the image's back‐
414 ground color. (255,255,255) is white (all pixels on). (0,0,0) is
415 black (all pixels off). (255,0,0) is fully saturated red.
416 (127,127,127) is 50% gray. You can find plenty of examples in
417 /usr/X11/lib/X11/rgb.txt.
418
419 If no colors are allocated, then this function returns -1.
420
421 Example:
422
423 $white = $myImage->colorAllocate(0,0,0); #background color
424 $black = $myImage->colorAllocate(255,255,255);
425 $peachpuff = $myImage->colorAllocate(255,218,185);
426
427 $index = $image->colorAllocateAlpha(reg,green,blue,alpha)
428 This allocates a color with the specified red, green, and blue com‐
429 ponents, plus the specified alpha channel. The alpha value may
430 range from 0 (opaque) to 127 (transparent). The "alphaBlending"
431 function changes the way this alpha channel affects the resulting
432 image.
433
434 $image->colorDeallocate(colorIndex)
435 This marks the color at the specified index as being ripe for real‐
436 location. The next time colorAllocate is used, this entry will be
437 replaced. You can call this method several times to deallocate
438 multiple colors. There's no function result from this call.
439
440 Example:
441
442 $myImage->colorDeallocate($peachpuff);
443 $peachy = $myImage->colorAllocate(255,210,185);
444
445 $index = $image->colorClosest(red,green,blue)
446 This returns the index of the color closest in the color table to
447 the red green and blue components specified. If no colors have yet
448 been allocated, then this call returns -1.
449
450 Example:
451
452 $apricot = $myImage->colorClosest(255,200,180);
453
454 $index = $image->colorClosestHWB(red,green,blue)
455 This also attempts to return the color closest in the color table
456 to the red green and blue components specified. It uses a
457 Hue/White/Black color representation to make the selected color
458 more likely to match human perceptions of similar colors.
459
460 If no colors have yet been allocated, then this call returns -1.
461
462 Example:
463
464 $mostred = $myImage->colorClosestHWB(255,0,0);
465
466 $index = $image->colorExact(red,green,blue)
467 This returns the index of a color that exactly matches the speci‐
468 fied red green and blue components. If such a color is not in the
469 color table, this call returns -1.
470
471 $rosey = $myImage->colorExact(255,100,80);
472 warn "Everything's coming up roses.\n" if $rosey >= 0;
473
474 $index = $image->colorResolve(red,green,blue)
475 This returns the index of a color that exactly matches the speci‐
476 fied red green and blue components. If such a color is not in the
477 color table and there is room, then this method allocates the color
478 in the color table and returns its index.
479
480 $rosey = $myImage->colorResolve(255,100,80);
481 warn "Everything's coming up roses.\n" if $rosey >= 0;
482
483 $colorsTotal = $image->colorsTotal object method
484 This returns the total number of colors allocated in the object.
485
486 $maxColors = $myImage->colorsTotal;
487
488 In the case of a TrueColor image, this call will return undef.
489
490 $index = $image->getPixel(x,y) object method
491 This returns the color table index underneath the specified point.
492 It can be combined with rgb() to obtain the rgb color underneath
493 the pixel.
494
495 Example:
496
497 $index = $myImage->getPixel(20,100);
498 ($r,$g,$b) = $myImage->rgb($index);
499
500 ($red,$green,$blue) = $image->rgb($index)
501 This returns a list containing the red, green and blue components
502 of the specified color index.
503
504 Example:
505
506 @RGB = $myImage->rgb($peachy);
507
508 $image->transparent($colorIndex)
509 This marks the color at the specified index as being transparent.
510 Portions of the image drawn in this color will be invisible. This
511 is useful for creating paintbrushes of odd shapes, as well as for
512 making PNG backgrounds transparent for displaying on the Web. Only
513 one color can be transparent at any time. To disable transparency,
514 specify -1 for the index.
515
516 If you call this method without any parameters, it will return the
517 current index of the transparent color, or -1 if none.
518
519 Example:
520
521 open(PNG,"test.png");
522 $im = newFromPng GD::Image(PNG);
523 $white = $im->colorClosest(255,255,255); # find white
524 $im->transparent($white);
525 binmode STDOUT;
526 print $im->png;
527
528 Special Colors
529
530 GD implements a number of special colors that can be used to achieve
531 special effects. They are constants defined in the GD:: namespace, but
532 automatically exported into your namespace when the GD module is
533 loaded.
534
535 $image->setBrush($image)
536 You can draw lines and shapes using a brush pattern. Brushes are
537 just images that you can create and manipulate in the usual way.
538 When you draw with them, their contents are used for the color and
539 shape of the lines.
540
541 To make a brushed line, you must create or load the brush first,
542 then assign it to the image using setBrush(). You can then draw in
543 that with that brush using the gdBrushed special color. It's often
544 useful to set the background of the brush to transparent so that
545 the non-colored parts don't overwrite other parts of your image.
546
547 Example:
548
549 # Create a brush at an angle
550 $diagonal_brush = new GD::Image(5,5);
551 $white = $diagonal_brush->colorAllocate(255,255,255);
552 $black = $diagonal_brush->colorAllocate(0,0,0);
553 $diagonal_brush->transparent($white);
554 $diagonal_brush->line(0,4,4,0,$black); # NE diagonal
555
556 # Set the brush
557 $myImage->setBrush($diagonal_brush);
558
559 # Draw a circle using the brush
560 $myImage->arc(50,50,25,25,0,360,gdBrushed);
561
562 $image->setThickness($thickness)
563 Lines drawn with line(), rectangle(), arc(), and so forth are 1
564 pixel thick by default. Call setThickness() to change the line
565 drawing width.
566
567 $image->setStyle(@colors)
568 Styled lines consist of an arbitrary series of repeated colors and
569 are useful for generating dotted and dashed lines. To create a
570 styled line, use setStyle() to specify a repeating series of col‐
571 ors. It accepts an array consisting of one or more color indexes.
572 Then draw using the gdStyled special color. Another special color,
573 gdTransparent can be used to introduce holes in the line, as the
574 example shows.
575
576 Example:
577
578 # Set a style consisting of 4 pixels of yellow,
579 # 4 pixels of blue, and a 2 pixel gap
580 $myImage->setStyle($yellow,$yellow,$yellow,$yellow,
581 $blue,$blue,$blue,$blue,
582 gdTransparent,gdTransparent);
583 $myImage->arc(50,50,25,25,0,360,gdStyled);
584
585 To combine the "gdStyled" and "gdBrushed" behaviors, you can spec‐
586 ify "gdStyledBrushed". In this case, a pixel from the current
587 brush pattern is rendered wherever the color specified in set‐
588 Style() is neither gdTransparent nor 0.
589
590 gdTiled
591 Draw filled shapes and flood fills using a pattern. The pattern is
592 just another image. The image will be tiled multiple times in
593 order to fill the required space, creating wallpaper effects. You
594 must call "setTile" in order to define the particular tile pattern
595 you'll use for drawing when you specify the gdTiled color.
596 details.
597
598 gdStyled
599 The gdStyled color is used for creating dashed and dotted lines. A
600 styled line can contain any series of colors and is created using
601 the setStyled() command.
602
603 gdAntiAliased
604 The "gdAntiAliased" color is used for drawing lines with antialias‐
605 ing turned on. Antialiasing will blend the jagged edges of lines
606 with the background, creating a smoother look. The actual color
607 drawn is set with setAntiAliased().
608
609 $image->setAntiAliased($color)
610 "Antialiasing" is a process by which jagged edges associated with
611 line drawing can be reduced by blending the foreground color with
612 an appropriate percentage of the background, depending on how much
613 of the pixel in question is actually within the boundaries of the
614 line being drawn. All line-drawing methods, such as line() and
615 polygon, will draw antialiased lines if the special "color" gdAn‐
616 tiAliased is used when calling them.
617
618 setAntiAliased() is used to specify the actual foreground color to
619 be used when drawing antialiased lines. You may set any color to be
620 the foreground, however as of libgd version 2.0.12 an alpha channel
621 component is not supported.
622
623 Antialiased lines can be drawn on both truecolor and palette-based
624 images. However, attempts to draw antialiased lines on highly com‐
625 plex palette-based backgrounds may not give satisfactory results,
626 due to the limited number of colors available in the palette.
627 Antialiased line-drawing on simple backgrounds should work well
628 with palette-based images; otherwise create or fetch a truecolor
629 image instead.
630
631 $image->setAntiAliasedDontBlend($color,[$flag])
632 Normally, when drawing lines with the special gdAntiAliased
633 "color," blending with the background to reduce jagged edges is the
634 desired behavior. However, when it is desired that lines not be
635 blended with one particular color when it is encountered in the
636 background, the setAntiAliasedDontBlend() method can be used to
637 indicate the special color that the foreground should stand out
638 more clearly against.
639
640 Once turned on, you can turn this feature off by calling setAn‐
641 tiAliasedDontBlend() with a second argument of 0:
642
643 $image->setAntiAliasedDontBlend($color,0);
644
645 Drawing Commands
646
647 These methods allow you to draw lines, rectangles, and ellipses, as
648 well as to perform various special operations like flood-fill.
649
650 $image->setPixel($x,$y,$color)
651 This sets the pixel at (x,y) to the specified color index. No
652 value is returned from this method. The coordinate system starts
653 at the upper left at (0,0) and gets larger as you go down and to
654 the right. You can use a real color, or one of the special colors
655 gdBrushed, gdStyled and gdStyledBrushed can be specified.
656
657 Example:
658
659 # This assumes $peach already allocated
660 $myImage->setPixel(50,50,$peach);
661
662 $image->line($x1,$y1,$x2,$y2,$color)
663 This draws a line from (x1,y1) to (x2,y2) of the specified color.
664 You can use a real color, or one of the special colors gdBrushed,
665 gdStyled and gdStyledBrushed.
666
667 Example:
668
669 # Draw a diagonal line using the currently defined
670 # paintbrush pattern.
671 $myImage->line(0,0,150,150,gdBrushed);
672
673 $image->dashedLine($x1,$y1,$x2,$y2,$color)
674 DEPRECATED: The libgd library provides this method solely for back‐
675 ward compatibility with libgd version 1.0, and there have been
676 reports that it no longer works as expected. Please use the set‐
677 Style() and gdStyled methods as described below.
678
679 This draws a dashed line from (x1,y1) to (x2,y2) in the specified
680 color. A more powerful way to generate arbitrary dashed and dotted
681 lines is to use the setStyle() method described below and to draw
682 with the special color gdStyled.
683
684 Example:
685
686 $myImage->dashedLine(0,0,150,150,$blue);
687
688 $image->rectangle($x1,$y1,$x2,$y2,$color)
689 This draws a rectangle with the specified color. (x1,y1) and
690 (x2,y2) are the upper left and lower right corners respectively.
691 Both real color indexes and the special colors gdBrushed, gdStyled
692 and gdStyledBrushed are accepted.
693
694 Example:
695
696 $myImage->rectangle(10,10,100,100,$rose);
697
698 $image->filledRectangle($x1,$y1,$x2,$y2,$color)
699 This draws a rectangle filed with the specified color. You can use
700 a real color, or the special fill color gdTiled to fill the polygon
701 with a pattern.
702
703 Example:
704
705 # read in a fill pattern and set it
706 $tile = newFromPng GD::Image('happyface.png');
707 $myImage->setTile($tile);
708
709 # draw the rectangle, filling it with the pattern
710 $myImage->filledRectangle(10,10,150,200,gdTiled);
711
712 $image->openPolygon($polygon,$color)
713 This draws a polygon with the specified color. The polygon must be
714 created first (see below). The polygon must have at least three
715 vertices. If the last vertex doesn't close the polygon, the method
716 will close it for you. Both real color indexes and the special
717 colors gdBrushed, gdStyled and gdStyledBrushed can be specified.
718
719 Example:
720
721 $poly = new GD::Polygon;
722 $poly->addPt(50,0);
723 $poly->addPt(99,99);
724 $poly->addPt(0,99);
725 $myImage->openPolygon($poly,$blue);
726
727 $image->unclosedPolygon($polygon,$color)
728 This draws a sequence of connected lines with the specified color,
729 without connecting the first and last point to a closed polygon.
730 The polygon must be created first (see below). The polygon must
731 have at least three vertices. Both real color indexes and the spe‐
732 cial colors gdBrushed, gdStyled and gdStyledBrushed can be speci‐
733 fied.
734
735 You need libgd 2.0.33 or higher to use this feature.
736
737 Example:
738
739 $poly = new GD::Polygon;
740 $poly->addPt(50,0);
741 $poly->addPt(99,99);
742 $poly->addPt(0,99);
743 $myImage->unclosedPolygon($poly,$blue);
744
745 $image->filledPolygon($poly,$color)
746 This draws a polygon filled with the specified color. You can use
747 a real color, or the special fill color gdTiled to fill the polygon
748 with a pattern.
749
750 Example:
751
752 # make a polygon
753 $poly = new GD::Polygon;
754 $poly->addPt(50,0);
755 $poly->addPt(99,99);
756 $poly->addPt(0,99);
757
758 # draw the polygon, filling it with a color
759 $myImage->filledPolygon($poly,$peachpuff);
760
761 $image->ellipse($cx,$cy,$width,$height,$color)
762 $image->filledEllipse($cx,$cy,$width,$height,$color)
763 These methods() draw ellipses. ($cx,$cy) is the center of the arc,
764 and ($width,$height) specify the ellipse width and height, respec‐
765 tively. filledEllipse() is like Ellipse() except that the former
766 produces filled versions of the ellipse.
767
768 $image->arc($cx,$cy,$width,$height,$start,$end,$color)
769 This draws arcs and ellipses. (cx,cy) are the center of the arc,
770 and (width,height) specify the width and height, respectively. The
771 portion of the ellipse covered by the arc are controlled by start
772 and end, both of which are given in degrees from 0 to 360. Zero is
773 at the top of the ellipse, and angles increase clockwise. To spec‐
774 ify a complete ellipse, use 0 and 360 as the starting and ending
775 angles. To draw a circle, use the same value for width and height.
776
777 You can specify a normal color or one of the special colors
778 gdBrushed, gdStyled, or gdStyledBrushed.
779
780 Example:
781
782 # draw a semicircle centered at 100,100
783 $myImage->arc(100,100,50,50,0,180,$blue);
784
785 $image->filledArc($cx,$cy,$width,$height,$start,$end,$color
786 [,$arc_style])
787 This method is like arc() except that it colors in the pie wedge
788 with the selected color. $arc_style is optional. If present it is
789 a bitwise OR of the following constants:
790
791 gdArc connect start & end points of arc with a rounded edge
792 gdChord connect start & end points of arc with a straight line
793 gdPie synonym for gdChord
794 gdNoFill outline the arc or chord
795 gdEdged connect beginning and ending of the arc to the center
796
797 gdArc and gdChord are mutually exclusive. gdChord just connects
798 the starting and ending angles with a straight line, while gdArc
799 produces a rounded edge. gdPie is a synonym for gdArc. gdNoFill
800 indicates that the arc or chord should be outlined, not filled.
801 gdEdged, used together with gdNoFill, indicates that the beginning
802 and ending angles should be connected to the center; this is a good
803 way to outline (rather than fill) a "pie slice."
804
805 Example:
806
807 $image->filledArc(100,100,50,50,0,90,$blue,gdEdged⎪gdNoFill);
808
809 $image->fill($x,$y,$color)
810 This method flood-fills regions with the specified color. The
811 color will spread through the image, starting at point (x,y), until
812 it is stopped by a pixel of a different color from the starting
813 pixel (this is similar to the "paintbucket" in many popular drawing
814 toys). You can specify a normal color, or the special color
815 gdTiled, to flood-fill with patterns.
816
817 Example:
818
819 # Draw a rectangle, and then make its interior blue
820 $myImage->rectangle(10,10,100,100,$black);
821 $myImage->fill(50,50,$blue);
822
823 $image->fillToBorder($x,$y,$bordercolor,$color)
824 Like "fill", this method flood-fills regions with the specified
825 color, starting at position (x,y). However, instead of stopping
826 when it hits a pixel of a different color than the starting pixel,
827 flooding will only stop when it hits the color specified by border‐
828 color. You must specify a normal indexed color for the border‐
829 color. However, you are free to use the gdTiled color for the
830 fill.
831
832 Example:
833
834 # This has the same effect as the previous example
835 $myImage->rectangle(10,10,100,100,$black);
836 $myImage->fillToBorder(50,50,$black,$blue);
837
838 Image Copying Commands
839
840 Two methods are provided for copying a rectangular region from one
841 image to another. One method copies a region without resizing it. The
842 other allows you to stretch the region during the copy operation.
843
844 With either of these methods it is important to know that the routines
845 will attempt to flesh out the destination image's color table to match
846 the colors that are being copied from the source. If the destination's
847 color table is already full, then the routines will attempt to find the
848 best match, with varying results.
849
850 $image->copy($sourceImage,$dstX,$dstY,
851 $srcX,$srcY,$width,$height)
852
853 This is the simplest of the several copy operations, copying the
854 specified region from the source image to the destination image
855 (the one performing the method call). (srcX,srcY) specify the
856 upper left corner of a rectangle in the source image, and
857 (width,height) give the width and height of the region to copy.
858 (dstX,dstY) control where in the destination image to stamp the
859 copy. You can use the same image for both the source and the des‐
860 tination, but the source and destination regions must not overlap
861 or strange things will happen.
862
863 Example:
864
865 $myImage = new GD::Image(100,100);
866 ... various drawing stuff ...
867 $srcImage = new GD::Image(50,50);
868 ... more drawing stuff ...
869 # copy a 25x25 pixel region from $srcImage to
870 # the rectangle starting at (10,10) in $myImage
871 $myImage->copy($srcImage,10,10,0,0,25,25);
872
873 $image->clone()
874 Make a copy of the image and return it as a new object. The new
875 image will look identical. However, it may differ in the size of
876 the color palette and other nonessential details.
877
878 Example:
879
880 $myImage = new GD::Image(100,100);
881 ... various drawing stuff ...
882 $copy = $myImage->clone;
883
884 $image->copyMerge($sourceImage,$dstX,$dstY,
885 $srcX,$srcY,$width,$height,$percent)
886
887 This copies the indicated rectangle from the source image to the
888 destination image, merging the colors to the extent specified by
889 percent (an integer between 0 and 100). Specifying 100% has the
890 same effect as copy() -- replacing the destination pixels with the
891 source image. This is most useful for highlighting an area by
892 merging in a solid rectangle.
893
894 Example:
895
896 $myImage = new GD::Image(100,100);
897 ... various drawing stuff ...
898 $redImage = new GD::Image(50,50);
899 ... more drawing stuff ...
900 # copy a 25x25 pixel region from $srcImage to
901 # the rectangle starting at (10,10) in $myImage, merging 50%
902 $myImage->copyMerge($srcImage,10,10,0,0,25,25,50);
903
904 $image->copyMergeGray($sourceImage,$dstX,$dstY,
905 $srcX,$srcY,$width,$height,$percent)
906
907 This is identical to copyMerge() except that it preserves the hue
908 of the source by converting all the pixels of the destination rec‐
909 tangle to grayscale before merging.
910
911 $image->copyResized($sourceImage,$dstX,$dstY,
912 $srcX,$srcY,$destW,$destH,$srcW,$srcH)
913
914 This method is similar to copy() but allows you to choose different
915 sizes for the source and destination rectangles. The source and
916 destination rectangle's are specified independently by (srcW,srcH)
917 and (destW,destH) respectively. copyResized() will stretch or
918 shrink the image to accommodate the size requirements.
919
920 Example:
921
922 $myImage = new GD::Image(100,100);
923 ... various drawing stuff ...
924 $srcImage = new GD::Image(50,50);
925 ... more drawing stuff ...
926 # copy a 25x25 pixel region from $srcImage to
927 # a larger rectangle starting at (10,10) in $myImage
928 $myImage->copyResized($srcImage,10,10,0,0,50,50,25,25);
929
930 $image->copyResampled($sourceImage,$dstX,$dstY,
931 $srcX,$srcY,$destW,$destH,$srcW,$srcH)
932
933 This method is similar to copyResized() but provides "smooth" copy‐
934 ing from a large image to a smaller one, using a weighted average
935 of the pixels of the source area rather than selecting one repre‐
936 sentative pixel. This method is identical to copyResized() when the
937 destination image is a palette image.
938
939 $image->copyRotated($sourceImage,$dstX,$dstY,
940 $srcX,$srcY,$width,$height,$angle)
941
942 Like copyResized() but the $angle argument specifies an arbitrary
943 amount to rotate the image clockwise (in degrees). In addition,
944 $dstX and $dstY species the center of the destination image, and
945 not the top left corner.
946
947 $image->trueColorToPalette([$dither], [$colors])
948 This method converts a truecolor image to a palette image. The code
949 for this function was originally drawn from the Independent JPEG
950 Group library code, which is excellent. The code has been modified
951 to preserve as much alpha channel information as possible in the
952 resulting palette, in addition to preserving colors as well as pos‐
953 sible. This does not work as well as might be hoped. It is usually
954 best to simply produce a truecolor output image instead, which
955 guarantees the highest output quality. Both the dithering (0/1,
956 default=0) and maximum number of colors used (<=256, default =
957 gdMaxColors) can be specified.
958
959 Image Transformation Commands
960
961 Gd also provides some common image transformations:
962
963 $image = $sourceImage->copyRotate90()
964 $image = $sourceImage->copyRotate180()
965 $image = $sourceImage->copyRotate270()
966 $image = $sourceImage->copyFlipHorizontal()
967 $image = $sourceImage->copyFlipVertical()
968 $image = $sourceImage->copyTranspose()
969 $image = $sourceImage->copyReverseTranspose()
970 These methods can be used to rotate, flip, or transpose an image.
971 The result of the method is a copy of the image.
972
973 $image->rotate180()
974 $image->flipHorizontal()
975 $image->flipVertical()
976 These methods are similar to the copy* versions, but instead modify
977 the image in place.
978
979 Character and String Drawing
980
981 GD allows you to draw characters and strings, either in normal horizon‐
982 tal orientation or rotated 90 degrees. These routines use a GD::Font
983 object, described in more detail below. There are four built-in
984 monospaced fonts, available in the global variables gdGiantFont,
985 gdLargeFont, gdMediumBoldFont, gdSmallFont and gdTinyFont.
986
987 In addition, you can use the load() method to load GD-formatted bitmap
988 font files at runtime. You can create these bitmap files from X11 BDF-
989 format files using the bdf2gd.pl script, which should have been
990 installed with GD (see the bdf_scripts directory if it wasn't). The
991 format happens to be identical to the old-style MSDOS bitmap ".fnt"
992 files, so you can use one of those directly if you happen to have one.
993
994 For writing proportional scaleable fonts, GD offers the stringFT()
995 method, which allows you to load and render any TrueType font on your
996 system.
997
998 $image->string($font,$x,$y,$string,$color)
999 This method draws a string starting at position (x,y) in the speci‐
1000 fied font and color. Your choices of fonts are gdSmallFont,
1001 gdMediumBoldFont, gdTinyFont, gdLargeFont and gdGiantFont.
1002
1003 Example:
1004
1005 $myImage->string(gdSmallFont,2,10,"Peachy Keen",$peach);
1006
1007 $image->stringUp($font,$x,$y,$string,$color)
1008 Just like the previous call, but draws the text rotated counter‐
1009 clockwise 90 degrees.
1010
1011 $image->char($font,$x,$y,$char,$color)
1012 $image->charUp($font,$x,$y,$char,$color)
1013 These methods draw single characters at position (x,y) in the spec‐
1014 ified font and color. They're carry-overs from the C interface,
1015 where there is a distinction between characters and strings. Perl
1016 is insensible to such subtle distinctions.
1017
1018 $font = GD::Font->load($fontfilepath)
1019 This method dynamically loads a font file, returning a font that
1020 you can use in subsequent calls to drawing methods. For example:
1021
1022 my $courier = GD::Font->load('./courierR12.fnt') or die "Can't load font";
1023 $image->string($courier,2,10,"Peachy Keen",$peach);
1024
1025 Font files must be in GD binary format, as described above.
1026
1027 @bounds = $image->stringFT($fgcolor,$font‐
1028 name,$ptsize,$angle,$x,$y,$string)
1029 @bounds = GD::Image->stringFT($fgcolor,$font‐
1030 name,$ptsize,$angle,$x,$y,$string)
1031 @bounds = $image->stringFT($fgcolor,$font‐
1032 name,$ptsize,$angle,$x,$y,$string,\%options)
1033 This method uses TrueType to draw a scaled, antialiased string
1034 using the TrueType vector font of your choice. It requires that
1035 libgd to have been compiled with TrueType support, and for the
1036 appropriate TrueType font to be installed on your system.
1037
1038 The arguments are as follows:
1039
1040 fgcolor Color index to draw the string in
1041 fontname A path to the TrueType (.ttf) font file or a font pattern.
1042 ptsize The desired point size (may be fractional)
1043 angle The rotation angle, in radians (positive values rotate counter clockwise)
1044 x,y X and Y coordinates to start drawing the string
1045 string The string itself
1046
1047 If successful, the method returns an eight-element list giving the
1048 boundaries of the rendered string:
1049
1050 @bounds[0,1] Lower left corner (x,y)
1051 @bounds[2,3] Lower right corner (x,y)
1052 @bounds[4,5] Upper right corner (x,y)
1053 @bounds[6,7] Upper left corner (x,y)
1054
1055 In case of an error (such as the font not being available, or FT
1056 support not being available), the method returns an empty list and
1057 sets $@ to the error message.
1058
1059 The string may contain UTF-8 sequences like: "À"
1060
1061 You may also call this method from the GD::Image class name, in
1062 which case it doesn't do any actual drawing, but returns the bound‐
1063 ing box using an inexpensive operation. You can use this to per‐
1064 form layout operations prior to drawing.
1065
1066 Using a negative color index will disable antialiasing, as
1067 described in the libgd manual page at
1068 <http://www.boutell.com/gd/manual2.0.9.html#gdImageStringFT>.
1069
1070 An optional 8th argument allows you to pass a hashref of options to
1071 stringFT(). Several hashkeys are recognized: linespacing, charmap,
1072 resolution, and kerning.
1073
1074 The value of linespacing is supposed to be a multiple of the char‐
1075 acter height, so setting linespacing to 2.0 will result in double-
1076 spaced lines of text. However the current version of libgd
1077 (2.0.12) does not do this. Instead the linespacing seems to be
1078 double what is provided in this argument. So use a spacing of 0.5
1079 to get separation of exactly one line of text. In practice, a
1080 spacing of 0.6 seems to give nice results. Another thing to watch
1081 out for is that successive lines of text should be separated by the
1082 "\r\n" characters, not just "\n".
1083
1084 The value of charmap is one of "Unicode", "Shift_JIS" and "Big5".
1085 The interaction between Perl, Unicode and libgd is not clear to me,
1086 and you should experiment a bit if you want to use this feature.
1087
1088 The value of resolution is the vertical and horizontal resolution,
1089 in DPI, in the format "hdpi,vdpi". If present, the resolution will
1090 be passed to the Freetype rendering engine as a hint to improve the
1091 appearance of the rendered font.
1092
1093 The value of kerning is a flag. Set it to false to turn off the
1094 default kerning of text.
1095
1096 Example:
1097
1098 $gd->stringFT($black,'/dosc/windows/Fonts/pala.ttf',40,0,20,90,
1099 "hi there\r\nbye now",
1100 {linespacing=>0.6,
1101 charmap => 'Unicode',
1102 });
1103
1104 If GD was compiled with fontconfig support, and the fontconfig
1105 library is available on your system, then you can use a font name
1106 pattern instead of a path. Patterns are described in fontconfig
1107 and will look something like this "Times:italic". For backward
1108 compatibility, this feature is disabled by default. You must
1109 enable it by calling useFontConfig(1) prior to the stringFT() call.
1110
1111 $image->useFontConfig(1);
1112
1113 For backward compatibility with older versions of the FreeType
1114 library, the alias stringTTF() is also recognized.
1115
1116 $hasfontconfig = $image->useFontConfig($flag)
1117 Call useFontConfig() with a value of 1 in order to enable support
1118 for fontconfig font patterns (see stringFT). Regardless of the
1119 value of $flag, this method will return a true value if the font‐
1120 config library is present, or false otherwise.
1121
1122 $result = $image-stringFTCircle($cx,$cy,$radius,$textRadius,$fillPor‐
1123 tion,$font,$points,$top,$bottom,$fgcolor)>
1124 This draws text in a circle. Currently (libgd 2.0.33) this function
1125 does not work for me, but the interface is provided for complete‐
1126 ness. The call signature is somewhat complex. Here is an excerpt
1127 from the libgd manual page:
1128
1129 Draws the text strings specified by top and bottom on the image,
1130 curved along the edge of a circle of radius radius, with its center
1131 at cx and cy. top is written clockwise along the top; bottom is
1132 written counterclockwise along the bottom. textRadius determines
1133 the "height" of each character; if textRadius is 1/2 of radius,
1134 characters extend halfway from the edge to the center. fillPortion
1135 varies from 0 to 1.0, with useful values from about 0.4 to 0.9, and
1136 determines how much of the 180 degrees of arc assigned to each sec‐
1137 tion of text is actually occupied by text; 0.9 looks better than
1138 1.0 which is rather crowded. font is a freetype font; see gdIm‐
1139 ageStringFT. points is passed to the freetype engine and has an
1140 effect on hinting; although the size of the text is determined by
1141 radius, textRadius, and fillPortion, you should pass a point size
1142 that "hints" appropriately -- if you know the text will be large,
1143 pass a large point size such as 24.0 to get the best results.
1144 fgcolor can be any color, and may have an alpha component, do
1145 blending, etc.
1146
1147 Returns a true value on success.
1148
1149 Alpha channels
1150
1151 The alpha channel methods allow you to control the way drawings are
1152 processed according to the alpha channel. When true color is turned on,
1153 colors are encoded as four bytes, in which the last three bytes are the
1154 RGB color values, and the first byte is the alpha channel. Therefore
1155 the hexadecimal representation of a non transparent RGB color will be:
1156 C=0x00(rr)(bb)(bb)
1157
1158 When alpha blending is turned on, you can use the first byte of the
1159 color to control the transparency, meaning that a rectangle painted
1160 with color 0x00(rr)(bb)(bb) will be opaque, and another one painted
1161 with 0x7f(rr)(gg)(bb) will be transparent. The Alpha value must be >= 0
1162 and <= 0x7f.
1163
1164 $image->alphaBlending($integer)
1165 The alphaBlending() method allows for two different modes of draw‐
1166 ing on truecolor images. In blending mode, which is on by default
1167 (libgd 2.0.2 and above), the alpha channel component of the color
1168 supplied to all drawing functions, such as "setPixel", determines
1169 how much of the underlying color should be allowed to shine
1170 through. As a result, GD automatically blends the existing color at
1171 that point with the drawing color, and stores the result in the
1172 image. The resulting pixel is opaque. In non-blending mode, the
1173 drawing color is copied literally with its alpha channel informa‐
1174 tion, replacing the destination pixel. Blending mode is not avail‐
1175 able when drawing on palette images.
1176
1177 Pass a value of 1 for blending mode, and 0 for non-blending mode.
1178
1179 $image->saveAlpha($saveAlpha)
1180 By default, GD (libgd 2.0.2 and above) does not attempt to save
1181 full alpha channel information (as opposed to single-color trans‐
1182 parency) when saving PNG images. (PNG is currently the only output
1183 format supported by gd which can accommodate alpha channel informa‐
1184 tion.) This saves space in the output file. If you wish to create
1185 an image with alpha channel information for use with tools that
1186 support it, call saveAlpha(1) to turn on saving of such informa‐
1187 tion, and call alphaBlending(0) to turn off alpha blending within
1188 the library so that alpha channel information is actually stored in
1189 the image rather than being composited immediately at the time that
1190 drawing functions are invoked.
1191
1192 Miscellaneous Image Methods
1193
1194 These are various utility methods that are useful in some circum‐
1195 stances.
1196
1197 $image->interlaced([$flag])
1198 This method sets or queries the image's interlaced setting. Inter‐
1199 lace produces a cool venetian blinds effect on certain viewers.
1200 Provide a true parameter to set the interlace attribute. Provide
1201 undef to disable it. Call the method without parameters to find
1202 out the current setting.
1203
1204 ($width,$height) = $image->getBounds()
1205 This method will return a two-member list containing the width and
1206 height of the image. You query but not change the size of the
1207 image once it's created.
1208
1209 $width = $image->width
1210 $height = $image->height
1211 Return the width and height of the image, respectively.
1212
1213 $is_truecolor = $image->isTrueColor()
1214 This method will return a Boolean representing whether the image is
1215 true color or not.
1216
1217 $flag = $image1->compare($image2)
1218 Compare two images and return a bitmap describing the differences
1219 found, if any. The return value must be logically ANDed with one
1220 or more constants in order to determine the differences. The fol‐
1221 lowing constants are available:
1222
1223 GD_CMP_IMAGE The two images look different
1224 GD_CMP_NUM_COLORS The two images have different numbers of colors
1225 GD_CMP_COLOR The two images' palettes differ
1226 GD_CMP_SIZE_X The two images differ in the horizontal dimension
1227 GD_CMP_SIZE_Y The two images differ in the vertical dimension
1228 GD_CMP_TRANSPARENT The two images have different transparency
1229 GD_CMP_BACKGROUND The two images have different background colors
1230 GD_CMP_INTERLACE The two images differ in their interlace
1231 GD_CMP_TRUECOLOR The two images are not both true color
1232
1233 The most important of these is GD_CMP_IMAGE, which will tell you
1234 whether the two images will look different, ignoring differences in
1235 the order of colors in the color palette and other invisible
1236 changes. The constants are not imported by default, but must be
1237 imported individually or by importing the :cmp tag. Example:
1238
1239 use GD qw(:DEFAULT :cmp);
1240 # get $image1 from somewhere
1241 # get $image2 from somewhere
1242 if ($image1->compare($image2) & GD_CMP_IMAGE) {
1243 warn "images differ!";
1244 }
1245
1246 $image->clip($x1,$y1,$x2,$y2)
1247 ($x1,$y1,$x2,$y2) = $image->clip
1248 Set or get the clipping rectangle. When the clipping rectangle is
1249 set, all drawing will be clipped to occur within this rectangle.
1250 The clipping rectangle is initially set to be equal to the bound‐
1251 aries of the whole image. Change it by calling clip() with the
1252 coordinates of the new clipping rectangle. Calling clip() without
1253 any arguments will return the current clipping rectangle.
1254
1255 $flag = $image->boundsSafe($x,$y)
1256 The boundsSafe() method will return true if the point indicated by
1257 ($x,$y) is within the clipping rectangle, or false if it is not.
1258 If the clipping rectangle has not been set, then it will return
1259 true if the point lies within the image boundaries.
1260
1262 A few primitive polygon creation and manipulation methods are provided.
1263 They aren't part of the Gd library, but I thought they might be handy
1264 to have around (they're borrowed from my qd.pl Quickdraw library).
1265 Also see GD::Polyline.
1266
1267 $poly = GD::Polygon->new
1268 Create an empty polygon with no vertices.
1269
1270 $poly = new GD::Polygon;
1271
1272 $poly->addPt($x,$y)
1273 Add point (x,y) to the polygon.
1274
1275 $poly->addPt(0,0);
1276 $poly->addPt(0,50);
1277 $poly->addPt(25,25);
1278 $myImage->fillPoly($poly,$blue);
1279
1280 ($x,$y) = $poly->getPt($index)
1281 Retrieve the point at the specified vertex.
1282
1283 ($x,$y) = $poly->getPt(2);
1284
1285 $poly->setPt($index,$x,$y)
1286 Change the value of an already existing vertex. It is an error to
1287 set a vertex that isn't already defined.
1288
1289 $poly->setPt(2,100,100);
1290
1291 ($x,$y) = $poly->deletePt($index)
1292 Delete the specified vertex, returning its value.
1293
1294 ($x,$y) = $poly->deletePt(1);
1295
1296 $poly->clear()
1297 Delete all vertices, restoring the polygon to its initial empty
1298 state.
1299
1300 $poly->toPt($dx,$dy)
1301 Draw from current vertex to a new vertex, using relative (dx,dy)
1302 coordinates. If this is the first point, act like addPt().
1303
1304 $poly->addPt(0,0);
1305 $poly->toPt(0,50);
1306 $poly->toPt(25,-25);
1307 $myImage->fillPoly($poly,$blue);
1308
1309 $vertex_count = $poly->length
1310 Return the number of vertices in the polygon.
1311
1312 $points = $poly->length;
1313
1314 @vertices = $poly->vertices
1315 Return a list of all the vertices in the polygon object. Each mem‐
1316 ber of the list is a reference to an (x,y) array.
1317
1318 @vertices = $poly->vertices;
1319 foreach $v (@vertices)
1320 print join(",",@$v),"\n";
1321 }
1322
1323 @rect = $poly->bounds
1324 Return the smallest rectangle that completely encloses the polygon.
1325 The return value is an array containing the (left,top,right,bottom)
1326 of the rectangle.
1327
1328 ($left,$top,$right,$bottom) = $poly->bounds;
1329
1330 $poly->offset($dx,$dy)
1331 Offset all the vertices of the polygon by the specified horizontal
1332 (dh) and vertical (dy) amounts. Positive numbers move the polygon
1333 down and to the right.
1334
1335 $poly->offset(10,30);
1336
1337 $poly->map($srcL,$srcT,$srcR,$srcB,$destL,$dstT,$dstR,$dstB)
1338 Map the polygon from a source rectangle to an equivalent position in
1339 a destination rectangle, moving it and resizing it as necessary.
1340 See polys.pl for an example of how this works. Both the source and
1341 destination rectangles are given in (left,top,right,bottom) coordi‐
1342 nates. For convenience, you can use the polygon's own bounding box
1343 as the source rectangle.
1344
1345 # Make the polygon really tall
1346 $poly->map($poly->bounds,0,0,50,200);
1347
1348 $poly->scale($sx,$sy)
1349 Scale each vertex of the polygon by the X and Y factors indicated by
1350 sx and sy. For example scale(2,2) will make the polygon twice as
1351 large. For best results, move the center of the polygon to position
1352 (0,0) before you scale, then move it back to its previous position.
1353
1354 $poly->transform($sx,$rx,$sy,$ry,$tx,$ty)
1355 Run each vertex of the polygon through a transformation matrix,
1356 where sx and sy are the X and Y scaling factors, rx and ry are the X
1357 and Y rotation factors, and tx and ty are X and Y offsets. See the
1358 Adobe PostScript Reference, page 154 for a full explanation, or
1359 experiment.
1360
1361 GD::Polyline
1362
1363 Please see GD::Polyline for information on creating open polygons and
1364 splines.
1365
1367 The libgd library (used by the Perl GD library) has built-in support
1368 for about half a dozen fonts, which were converted from public-domain X
1369 Windows fonts. For more fonts, compile libgd with TrueType support and
1370 use the stringFT() call.
1371
1372 If you wish to add more built-in fonts, the directory bdf_scripts con‐
1373 tains two contributed utilities that may help you convert X-Windows
1374 BDF-format fonts into the format that libgd uses internally. However
1375 these scripts were written for earlier versions of GD which included
1376 its own mini-gd library. These scripts will have to be adapted for use
1377 with libgd, and the libgd library itself will have to be recompiled and
1378 linked! Please do not contact me for help with these scripts: they are
1379 unsupported.
1380
1381 Each of these fonts is available both as an imported global (e.g. gdS‐
1382 mallFont) and as a package method (e.g. GD::Font->Small).
1383
1384 gdSmallFont
1385 GD::Font->Small
1386 This is the basic small font, "borrowed" from a well known public
1387 domain 6x12 font.
1388
1389 gdLargeFont
1390 GD::Font->Large
1391 This is the basic large font, "borrowed" from a well known public
1392 domain 8x16 font.
1393
1394 gdMediumBoldFont
1395 GD::Font->MediumBold
1396 This is a bold font intermediate in size between the small and
1397 large fonts, borrowed from a public domain 7x13 font;
1398
1399 gdTinyFont
1400 GD::Font->Tiny
1401 This is a tiny, almost unreadable font, 5x8 pixels wide.
1402
1403 gdGiantFont
1404 GD::Font->Giant
1405 This is a 9x15 bold font converted by Jan Pazdziora from a sans
1406 serif X11 font.
1407
1408 $font->nchars
1409 This returns the number of characters in the font.
1410
1411 print "The large font contains ",gdLargeFont->nchars," characters\n";
1412
1413 $font->offset
1414 This returns the ASCII value of the first character in the font
1415
1416 $width = $font->width
1417 $height = $font->height
1418 "height"
1419 These return the width and height of the font.
1420
1421 ($w,$h) = (gdLargeFont->width,gdLargeFont->height);
1422
1424 libgd, the C-language version of gd, can be obtained at URL
1425 http://www.boutell.com/gd/. Directions for installing and using it can
1426 be found at that site. Please do not contact me for help with libgd.
1427
1429 The GD.pm interface is copyright 1995-2000, Lincoln D. Stein. It is
1430 distributed under the same terms as Perl itself. See the "Artistic
1431 License" in the Perl source code distribution for licensing terms.
1432
1433 The latest versions of GD.pm are available at
1434
1435 http://stein.cshl.org/WWW/software/GD
1436
1438 GD::Polyline, GD::SVG, GD::Simple, Image::Magick
1439
1440
1441
1442perl v5.8.8 2006-08-23 GD(3)