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
41 (version 2.01 or higher; see below). GD allows you to create color
42 drawings using a large number of graphics primitives, and emit the
43 drawings as 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,
62 simplified font handling, ability to work in polar coordinates,
63 HSV 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/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
105 initialize 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.
107 colors are added using a colorAllocate() method call. The three
108 parameters in each call are the red, green and blue (rgb) triples for
109 the 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
144 respectively), allowing for precise photograph-quality color usage.
145 If not specified, the image will use an 8-bit palette for
146 compatibility with older versions of libgd.
147
148 Alternatively, you may create a GD::Image object based on an
149 existing image by providing an open filehandle, a filename, or the
150 image 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 before creating new images. To switch back to palette based by
167 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
174 explicitly create an palette based or true color image regardless
175 of the 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
184 happens if the thing at the other end of the filehandle is not a
185 valid PNG file, the call returns undef. Notice that the call
186 doesn't automatically close the filehandle for you. But it does
187 call "binmode(FILEHANDLE)" for you, on platforms where this
188 matters.
189
190 You may use any of the following as the argument:
191
192 1) a simple filehandle, such as STDIN
193 2) a filehandle glob, such as *PNG
194 3) a reference to a glob, such as \*PNG
195 4) an IO::Handle object
196 5) the pathname of a file
197
198 In the latter case, newFromPng() will attempt to open the file for
199 you and read the PNG information from it.
200
201 Example1:
202
203 open (PNG,"barnswallow.png") || die;
204 $myImage = newFromPng GD::Image(\*PNG) || die;
205 close PNG;
206
207 Example2:
208 $myImage = newFromPng GD::Image('barnswallow.png');
209
210 To get information about the size and color usage of the
211 information, you can call the image query methods described below.
212 Images created by reading PNG images will be truecolor if the image
213 file itself is truecolor. To force the image to be palette-based,
214 pass a value of 0 in the optional $truecolor argument.
215
216 The newFromPngData() method will create a new GD::Image initialized
217 with the PNG format data contained in $data.
218
219 $image = GD::Image->newFromJpeg($file, [$truecolor])
220 $image = GD::Image->newFromJpegData($data, [$truecolor])
221 These methods will create an image from a JPEG file. They work
222 just like newFromPng() and newFromPngData(), and will accept the
223 same filehandle and pathname arguments.
224
225 Images created by reading JPEG images will always be truecolor. To
226 force the image to be palette-based, pass a value of 0 in the
227 optional $truecolor argument.
228
229 $image = GD::Image->newFromGif($file, [$truecolor])
230 $image = GD::Image->newFromGifData($data)
231 These methods will create an image from a GIF file. They work just
232 like newFromPng() and newFromPngData(), and will accept the same
233 filehandle and pathname arguments.
234
235 Images created from GIFs are always 8-bit palette images. To
236 convert to truecolor, you must create a truecolor image and then
237 perform a copy.
238
239 $image = GD::Image->newFromXbm($file, [$truecolor])
240 This works in exactly the same way as "newFromPng", but reads the
241 contents of an X Bitmap (black & white) file:
242
243 open (XBM,"coredump.xbm") || die;
244 $myImage = newFromXbm GD::Image(\*XBM) || die;
245 close XBM;
246
247 There is no newFromXbmData() function, because there is no
248 corresponding function in the gd library.
249
250 $image = GD::Image->newFromWBMP($file, [$truecolor])
251 This works in exactly the same way as "newFromPng", but reads the
252 contents of an Windows BMP Bitmap file:
253
254 open (BMP,"coredump.bmp") || die;
255 $myImage = newFromWBMP GD::Image(\*BMP) || die;
256 close BMP;
257
258 There is no newFromWBMPData() function, because there is no
259 corresponding function in the gd library.
260
261 $image = GD::Image->newFromGd($file)
262 $image = GD::Image->newFromGdData($data)
263 These methods initialize a GD::Image from a Gd file, filehandle, or
264 data. Gd is Tom Boutell's disk-based storage format, intended for
265 the rare case when you need to read and write the image to disk
266 quickly. It's not intended for regular use, because, unlike PNG or
267 JPEG, no image compression is performed and these files can become
268 BIG.
269
270 $myImage = newFromGd GD::Image("godzilla.gd") || die;
271 close GDF;
272
273 $image = GD::Image->newFromGd2($file)
274 $image = GD::Image->newFromGd2Data($data)
275 This works in exactly the same way as "newFromGd()" and
276 newFromGdData, but use the new compressed GD2 image format.
277
278 $image = GD::Image->newFromGd2Part($file,srcX,srcY,width,height)
279 This class method allows you to read in just a portion of a GD2
280 image file. In addition to a filehandle, it accepts the top-left
281 corner and dimensions (width,height) of the region of the image to
282 read. For example:
283
284 open (GDF,"godzilla.gd2") || die;
285 $myImage = GD::Image->newFromGd2Part(\*GDF,10,20,100,100) || die;
286 close GDF;
287
288 This reads a 100x100 square portion of the image starting from
289 position (10,20).
290
291 $image = GD::Image->newFromXpm($filename)
292 This creates a new GD::Image object starting from a filename. This
293 is unlike the other newFrom() functions because it does not take a
294 filehandle. This difference comes from an inconsistency in the
295 underlying gd library.
296
297 $myImage = newFromXpm GD::Image('earth.xpm') || die;
298
299 This function is only available if libgd was compiled with XPM
300 support.
301
302 NOTE: The libgd library is unable to read certain XPM files,
303 returning an all-black image instead.
304
305 $bool = GD::supportsFileType($filename, $is_writing)
306 This returns a TRUE or FALSE value, if libgd supports reading or
307 when the 2nd argument is 1, if libgd supports writing the given
308 filetype, depending on the filename extension. Only with libgd
309 versions >= gd-2.1.1.
310
311 Assuming LibGD is compiled with support for these image types, the
312 following extensions are supported:
313
314 .gif
315 .gd, .gd2
316 .wbmp
317 .bmp
318 .xbm
319 .tga
320 .png
321 .jpg, .jpeg
322 .tiff, .tif
323 .webp
324 .xpm
325
326 Filenames are parsed case-insensitively.
327
329 Once a GD::Image object is created, you can draw with it, copy it, and
330 merge two images. When you are finished manipulating the object, you
331 can convert it into a standard image file format to output or save to a
332 file.
333
334 Image Data Output Methods
335 The following methods convert the internal drawing format into standard
336 output file formats.
337
338 $pngdata = $image->png([$compression_level])
339 This returns the image data in PNG format. You can then print it,
340 pipe it to a display program, or write it to a file. Example:
341
342 $png_data = $myImage->png;
343 open (DISPLAY,"| display -") || die;
344 binmode DISPLAY;
345 print DISPLAY $png_data;
346 close DISPLAY;
347
348 Note the use of "binmode()". This is crucial for portability to
349 DOSish platforms.
350
351 The optional $compression_level argument controls the amount of
352 compression to apply to the output PNG image. Values range from
353 0-9, where 0 means no compression (largest files, highest quality)
354 and 9 means maximum compression (smallest files, worst quality). A
355 compression level of -1 uses the default compression level selected
356 when zlib was compiled on your system, and is the same as calling
357 png() with no argument. Be careful not to confuse this argument
358 with the jpeg() quality argument, which ranges from 0-100 and has
359 the opposite meaning from compression (higher numbers give higher
360 quality).
361
362 $gifdata = $image->gifanimbegin([$GlobalCM [, $Loops]])
363 For libgd version 2.0.33 and higher, this call begins an animated
364 GIF by returning the data that comprises animated gif image file
365 header. After you call this method, call gifanimadd() one or more
366 times to add the frames of the image. Then call gifanimend(). Each
367 frame must be the same width and height.
368
369 A typical sequence will look like this:
370
371 my $gifdata = $image->gifanimbegin;
372 $gifdata .= $image->gifanimadd; # first frame
373 for (1..100) {
374 # make a frame of right size
375 my $frame = GD::Image->new($image->getBounds);
376 add_frame_data($frame); # add the data for this frame
377 $gifdata .= $frame->gifanimadd; # add frame
378 }
379 $gifdata .= $image->gifanimend; # finish the animated GIF
380 print $gifdata; # write animated gif to STDOUT
381
382 If you do not wish to store the data in memory, you can print it to
383 stdout or a file.
384
385 The image that you call gifanimbegin on is used to set the image
386 size, color resolution and color map. If argument $GlobalCM is 1,
387 the image color map becomes the GIF89a global color map. If $Loops
388 is given and >= 0, the NETSCAPE2.0 application extension is
389 created, with looping count. Looping count 0 means forever.
390
391 $gifdata = $image->gifanimadd([$LocalCM [, $LeftOfs [, $TopOfs [,
392 $Delay [, $Disposal [, $previm]]]]]])
393 Returns the data that comprises one animated gif image frame. You
394 can then print it, pipe it to a display program, or write it to a
395 file. With $LeftOfs and $TopOfs you can place this frame in
396 different offset than (0,0) inside the image screen. Delay between
397 the previous frame and this frame is in 1/100s units. Disposal is
398 usually and by default 1. Compression is activated by giving the
399 previous image as a parameter. This function then compares the
400 images and only writes the changed pixels to the new frame in
401 animation. The Disposal parameter for optimized animations must be
402 set to 1, also for the first frame. $LeftOfs and $TopOfs
403 parameters are ignored for optimized frames.
404
405 $gifdata = $image->gifanimend()
406 Returns the data for end segment of animated gif file. It always
407 returns string ';'. This string must be printed to an animated gif
408 file after all image frames to properly terminate it according to
409 GIF file syntax. Image object is not used at all in this method.
410
411 $jpegdata = $image->jpeg([$quality])
412 This returns the image data in JPEG format. You can then print it,
413 pipe it to a display program, or write it to a file. You may pass
414 an optional quality score to jpeg() in order to control the JPEG
415 quality. This should be an integer between 0 and 100. Higher
416 quality scores give larger files and better image quality. If you
417 don't specify the quality, jpeg() will choose a good default.
418
419 $gifdata = $image->gif().
420 This returns the image data in GIF format. You can then print it,
421 pipe it to a display program, or write it to a file.
422
423 $gddata = $image->gd
424 This returns the image data in GD format. You can then print it,
425 pipe it to a display program, or write it to a file. Example:
426
427 binmode MYOUTFILE;
428 print MYOUTFILE $myImage->gd;
429
430 $gd2data = $image->gd2
431 Same as gd(), except that it returns the data in compressed GD2
432 format.
433
434 $wbmpdata = $image->wbmp([$foreground])
435 This returns the image data in WBMP format, which is a black-and-
436 white image format. Provide the index of the color to become the
437 foreground color. All other pixels will be considered background.
438
439 $success = $image->_file($filename)
440 Writes an image to a file in the format indicated by the filename,
441 with libgd versions >= gd-2.1.1.
442
443 File type is determined by the extension of the file name. See
444 "supportsFiletype" for an overview of the parsing.
445
446 For file types that require extra arguments, "_file" attempts to
447 use sane defaults:
448
449 C<gdImageGd2> chunk size = 0, compression is enabled.
450 C<gdImageJpeg> quality = -1 (i.e. the reasonable default)
451 C<gdImageWBMP> foreground is the darkest available color
452
453 Everything else is called with the two-argument function and so
454 will use the default values.
455
456 "_file" and the underlying libgd "gdImageFile" has some rudimentary
457 error detection and will return FALSE (0) if a detectable error
458 occurred. However, the image loaders do not normally return their
459 error status so a result of TRUE (1) does **not** mean the file was
460 saved successfully.
461
462 Color Control
463 These methods allow you to control and manipulate the GD::Image color
464 table for palette, non-truecolor images.
465
466 $index = $image->colorAllocate(red,green,blue)
467 This allocates a color with the specified red, green and blue
468 components and returns its index in the color table, if specified.
469 The first color allocated in this way becomes the image's
470 background color. (255,255,255) is white (all pixels on). (0,0,0)
471 is black (all pixels off). (255,0,0) is fully saturated red.
472 (127,127,127) is 50% gray. You can find plenty of examples in
473 /usr/X11/lib/X11/rgb.txt.
474
475 If no colors are allocated, then this function returns -1.
476
477 Example:
478
479 $black = $myImage->colorAllocate(0,0,0); #background color
480 $white = $myImage->colorAllocate(255,255,255);
481 $peachpuff = $myImage->colorAllocate(255,218,185);
482
483 $index = $image->colorAllocateAlpha(reg,green,blue,alpha)
484 This allocates a color with the specified red, green, and blue
485 components, plus the specified alpha channel. The alpha value may
486 range from 0 (opaque) to 127 (transparent). The "alphaBlending"
487 function changes the way this alpha channel affects the resulting
488 image.
489
490 $image->colorDeallocate(colorIndex)
491 This marks the color at the specified index as being ripe for
492 reallocation. The next time colorAllocate is used, this entry will
493 be replaced. You can call this method several times to deallocate
494 multiple colors. There's no function result from this call.
495
496 Example:
497
498 $myImage->colorDeallocate($peachpuff);
499 $peachy = $myImage->colorAllocate(255,210,185);
500
501 $index = $image->colorClosest(red,green,blue)
502 This returns the index of the color closest in the color table to
503 the red green and blue components specified. If no colors have yet
504 been allocated, then this call returns -1.
505
506 Example:
507
508 $apricot = $myImage->colorClosest(255,200,180);
509
510 $index = $image->colorClosestAlpha(red,green,blue,alpha)
511 This returns the index of the color closest in the color table to
512 the red green blue and alpha components specified. If no colors
513 have yet been allocated, then this call returns -1.
514
515 Example:
516
517 $apricot = $myImage->colorClosestAlpha(255,200,180,0);
518
519 $index = $image->colorClosestHWB(red,green,blue)
520 This also attempts to return the color closest in the color table
521 to the red green and blue components specified. It uses a
522 Hue/White/Black color representation to make the selected color
523 more likely to match human perceptions of similar colors.
524
525 If no colors have yet been allocated, then this call returns -1.
526
527 Example:
528
529 $mostred = $myImage->colorClosestHWB(255,0,0);
530
531 $index = $image->colorExact(red,green,blue)
532 This returns the index of a color that exactly matches the
533 specified red green and blue components. If such a color is not in
534 the color table, this call returns -1.
535
536 $rosey = $myImage->colorExact(255,100,80);
537 warn "Everything's coming up roses.\n" if $rosey >= 0;
538
539 $index = $image->colorExactAlpha(red,green,blue,alpha)
540 This returns the index of a color that exactly matches the
541 specified red green blue and alpha components. If such a color is
542 not in the color table, this call returns -1.
543
544 $rosey = $myImage->colorExactAlpha(255,100,80,0);
545 warn "Everything's coming up roses.\n" if $rosey >= 0;
546
547 $index = $image->colorResolve(red,green,blue)
548 This returns the index of a color that exactly matches the
549 specified red green and blue components. If such a color is not in
550 the color table and there is room, then this method allocates the
551 color in the color table and returns its index.
552
553 $rosey = $myImage->colorResolve(255,100,80);
554 warn "Everything's coming up roses.\n" if $rosey >= 0;
555
556 $index = $image->colorResolveAlpha(red,green,blue,alpha)
557 This returns the index of a color that exactly matches the
558 specified red green blue and alpha components. If such a color is
559 not in the color table and there is room, then this method
560 allocates the color in the color table and returns its index.
561
562 $rosey = $myImage->colorResolveAlpha(255,100,80,0);
563 warn "Everything's coming up roses.\n" if $rosey >= 0;
564
565 $colorsTotal = $image->colorsTotal object method
566 This returns the total number of colors allocated in the object.
567
568 $maxColors = $myImage->colorsTotal;
569
570 In the case of a TrueColor image, this call will return undef.
571
572 $index = $image->getPixel(x,y) object method
573 This returns the color table index underneath the specified point.
574 It can be combined with rgb() to obtain the rgb color underneath
575 the pixel.
576
577 Example:
578
579 $index = $myImage->getPixel(20,100);
580 ($r,$g,$b) = $myImage->rgb($index);
581
582 ($red,$green,$blue) = $image->rgb($index)
583 This returns a list containing the red, green and blue components
584 of the specified color index.
585
586 Example:
587
588 @RGB = $myImage->rgb($peachy);
589
590 ($alpha) = $image->alpha($index)
591 This returns an item containing the alpha component of the
592 specified color index.
593
594 Example:
595
596 @RGB = $myImage->rgb($peachy);
597
598 $image->transparent($colorIndex)
599 This marks the color at the specified index as being transparent.
600 Portions of the image drawn in this color will be invisible. This
601 is useful for creating paintbrushes of odd shapes, as well as for
602 making PNG backgrounds transparent for displaying on the Web. Only
603 one color can be transparent at any time. To disable transparency,
604 specify -1 for the index.
605
606 If you call this method without any parameters, it will return the
607 current index of the transparent color, or -1 if none.
608
609 Example:
610
611 open(PNG,"test.png");
612 $im = newFromPng GD::Image(PNG);
613 $white = $im->colorClosest(255,255,255); # find white
614 $im->transparent($white);
615 binmode STDOUT;
616 print $im->png;
617
618 Special Colors
619 GD implements a number of special colors that can be used to achieve
620 special effects. They are constants defined in the GD:: namespace, but
621 automatically exported into your namespace when the GD module is
622 loaded.
623
624 $image->setBrush($image)
625 You can draw lines and shapes using a brush pattern. Brushes are
626 just palette, not TrueColor, images that you can create and
627 manipulate in the usual way. When you draw with them, their
628 contents are used for the color and shape of the lines.
629
630 To make a brushed line, you must create or load the brush first,
631 then assign it to the image using setBrush(). You can then draw in
632 that with that brush using the gdBrushed special color. It's often
633 useful to set the background of the brush to transparent so that
634 the non-colored parts don't overwrite other parts of your image.
635
636 Example:
637
638 # Create a brush at an angle
639 $diagonal_brush = new GD::Image(5,5);
640 $white = $diagonal_brush->colorAllocate(255,255,255);
641 $black = $diagonal_brush->colorAllocate(0,0,0);
642 $diagonal_brush->transparent($white);
643 $diagonal_brush->line(0,4,4,0,$black); # NE diagonal
644
645 # Set the brush
646 $myImage->setBrush($diagonal_brush);
647
648 # Draw a circle using the brush
649 $myImage->arc(50,50,25,25,0,360,gdBrushed);
650
651 $image->setThickness($thickness)
652 Lines drawn with line(), rectangle(), arc(), and so forth are 1
653 pixel thick by default. Call setThickness() to change the line
654 drawing width.
655
656 $image->setStyle(@colors)
657 Styled lines consist of an arbitrary series of repeated colors and
658 are useful for generating dotted and dashed lines. To create a
659 styled line, use setStyle() to specify a repeating series of
660 colors. It accepts an array consisting of one or more color
661 indexes. Then draw using the gdStyled special color. Another
662 special color, gdTransparent can be used to introduce holes in the
663 line, as the example shows.
664
665 Example:
666
667 # Set a style consisting of 4 pixels of yellow,
668 # 4 pixels of blue, and a 2 pixel gap
669 $myImage->setStyle($yellow,$yellow,$yellow,$yellow,
670 $blue,$blue,$blue,$blue,
671 gdTransparent,gdTransparent);
672 $myImage->arc(50,50,25,25,0,360,gdStyled);
673
674 To combine the "gdStyled" and "gdBrushed" behaviors, you can
675 specify "gdStyledBrushed". In this case, a pixel from the current
676 brush pattern is rendered wherever the color specified in
677 setStyle() is neither gdTransparent nor 0.
678
679 gdTiled
680 Draw filled shapes and flood fills using a pattern. The pattern is
681 just another image. The image will be tiled multiple times in
682 order to fill the required space, creating wallpaper effects. You
683 must call "setTile" in order to define the particular tile pattern
684 you'll use for drawing when you specify the gdTiled color.
685 details.
686
687 gdStyled
688 The gdStyled color is used for creating dashed and dotted lines. A
689 styled line can contain any series of colors and is created using
690 the setStyled() command.
691
692 gdAntiAliased
693 The "gdAntiAliased" color is used for drawing lines with
694 antialiasing turned on. Antialiasing will blend the jagged edges
695 of lines with the background, creating a smoother look. The actual
696 color drawn is set with setAntiAliased().
697
698 $image->setAntiAliased($color)
699 "Antialiasing" is a process by which jagged edges associated with
700 line drawing can be reduced by blending the foreground color with
701 an appropriate percentage of the background, depending on how much
702 of the pixel in question is actually within the boundaries of the
703 line being drawn. All line-drawing methods, such as line() and
704 polygon, will draw antialiased lines if the special "color"
705 gdAntiAliased is used when calling them.
706
707 setAntiAliased() is used to specify the actual foreground color to
708 be used when drawing antialiased lines. You may set any color to be
709 the foreground, however as of libgd version 2.0.12 an alpha channel
710 component is not supported.
711
712 Antialiased lines can be drawn on both truecolor and palette-based
713 images. However, attempts to draw antialiased lines on highly
714 complex palette-based backgrounds may not give satisfactory
715 results, due to the limited number of colors available in the
716 palette. Antialiased line-drawing on simple backgrounds should work
717 well with palette-based images; otherwise create or fetch a
718 truecolor image instead. When using palette-based images, be sure
719 to allocate a broad spectrum of colors in order to have sufficient
720 colors for the antialiasing to use.
721
722 $image->setAntiAliasedDontBlend($color,[$flag])
723 Normally, when drawing lines with the special gdAntiAliased
724 "color," blending with the background to reduce jagged edges is the
725 desired behavior. However, when it is desired that lines not be
726 blended with one particular color when it is encountered in the
727 background, the setAntiAliasedDontBlend() method can be used to
728 indicate the special color that the foreground should stand out
729 more clearly against.
730
731 Once turned on, you can turn this feature off by calling
732 setAntiAliasedDontBlend() with a second argument of 0:
733
734 $image->setAntiAliasedDontBlend($color,0);
735
736 Drawing Commands
737 These methods allow you to draw lines, rectangles, and ellipses, as
738 well as to perform various special operations like flood-fill.
739
740 $image->setPixel($x,$y,$color)
741 This sets the pixel at (x,y) to the specified color index. No
742 value is returned from this method. The coordinate system starts
743 at the upper left at (0,0) and gets larger as you go down and to
744 the right. You can use a real color, or one of the special colors
745 gdBrushed, gdStyled and gdStyledBrushed can be specified.
746
747 Example:
748
749 # This assumes $peach already allocated
750 $myImage->setPixel(50,50,$peach);
751
752 $image->line($x1,$y1,$x2,$y2,$color)
753 This draws a line from (x1,y1) to (x2,y2) of the specified color.
754 You can use a real color, or one of the special colors gdBrushed,
755 gdStyled and gdStyledBrushed.
756
757 Example:
758
759 # Draw a diagonal line using the currently defined
760 # paintbrush pattern.
761 $myImage->line(0,0,150,150,gdBrushed);
762
763 $image->dashedLine($x1,$y1,$x2,$y2,$color)
764 DEPRECATED: The libgd library provides this method solely for
765 backward compatibility with libgd version 1.0, and there have been
766 reports that it no longer works as expected. Please use the
767 setStyle() and gdStyled methods as described below.
768
769 This draws a dashed line from (x1,y1) to (x2,y2) in the specified
770 color. A more powerful way to generate arbitrary dashed and dotted
771 lines is to use the setStyle() method described below and to draw
772 with the special color gdStyled.
773
774 Example:
775
776 $myImage->dashedLine(0,0,150,150,$blue);
777
778 $image->rectangle($x1,$y1,$x2,$y2,$color)
779 This draws a rectangle with the specified color. (x1,y1) and
780 (x2,y2) are the upper left and lower right corners respectively.
781 Both real color indexes and the special colors gdBrushed, gdStyled
782 and gdStyledBrushed are accepted.
783
784 Example:
785
786 $myImage->rectangle(10,10,100,100,$rose);
787
788 $image->filledRectangle($x1,$y1,$x2,$y2,$color) =item
789 $image->setTile($otherimage)
790 This draws a rectangle filled with the specified color. You can
791 use a real color, or the special fill color gdTiled to fill the
792 polygon with a pattern.
793
794 Example:
795
796 # read in a fill pattern and set it
797 $tile = newFromPng GD::Image('happyface.png');
798 $myImage->setTile($tile);
799
800 # draw the rectangle, filling it with the pattern
801 $myImage->filledRectangle(10,10,150,200,gdTiled);
802
803 $image->openPolygon($polygon,$color)
804 This draws a polygon with the specified color. The polygon must be
805 created first (see below). The polygon must have at least three
806 vertices. If the last vertex doesn't close the polygon, the method
807 will close it for you. Both real color indexes and the special
808 colors gdBrushed, gdStyled and gdStyledBrushed can be specified.
809
810 Example:
811
812 $poly = new GD::Polygon;
813 $poly->addPt(50,0);
814 $poly->addPt(99,99);
815 $poly->addPt(0,99);
816 $myImage->openPolygon($poly,$blue);
817
818 $image->unclosedPolygon($polygon,$color)
819 This draws a sequence of connected lines with the specified color,
820 without connecting the first and last point to a closed polygon.
821 The polygon must be created first (see below). The polygon must
822 have at least three vertices. Both real color indexes and the
823 special colors gdBrushed, gdStyled and gdStyledBrushed can be
824 specified.
825
826 You need libgd 2.0.33 or higher to use this feature.
827
828 Example:
829
830 $poly = new GD::Polygon;
831 $poly->addPt(50,0);
832 $poly->addPt(99,99);
833 $poly->addPt(0,99);
834 $myImage->unclosedPolygon($poly,$blue);
835
836 $image->filledPolygon($poly,$color)
837 This draws a polygon filled with the specified color. You can use
838 a real color, or the special fill color gdTiled to fill the polygon
839 with a pattern.
840
841 Example:
842
843 # make a polygon
844 $poly = new GD::Polygon;
845 $poly->addPt(50,0);
846 $poly->addPt(99,99);
847 $poly->addPt(0,99);
848
849 # draw the polygon, filling it with a color
850 $myImage->filledPolygon($poly,$peachpuff);
851
852 $image->ellipse($cx,$cy,$width,$height,$color)
853 $image->filledEllipse($cx,$cy,$width,$height,$color)
854 These methods() draw ellipses. ($cx,$cy) is the center of the arc,
855 and ($width,$height) specify the ellipse width and height,
856 respectively. filledEllipse() is like Ellipse() except that the
857 former produces filled versions of the ellipse.
858
859 $image->arc($cx,$cy,$width,$height,$start,$end,$color)
860 This draws arcs and ellipses. (cx,cy) are the center of the arc,
861 and (width,height) specify the width and height, respectively. The
862 portion of the ellipse covered by the arc are controlled by start
863 and end, both of which are given in degrees from 0 to 360. Zero is
864 at the right end of the ellipse, and angles increase clockwise. To
865 specify a complete ellipse, use 0 and 360 as the starting and
866 ending angles. To draw a circle, use the same value for width and
867 height.
868
869 You can specify a normal color or one of the special colors
870 gdBrushed, gdStyled, or gdStyledBrushed.
871
872 Example:
873
874 # draw a semicircle centered at 100,100
875 $myImage->arc(100,100,50,50,0,180,$blue);
876
877 $image->filledArc($cx,$cy,$width,$height,$start,$end,$color
878 [,$arc_style])
879 This method is like arc() except that it colors in the pie wedge
880 with the selected color. $arc_style is optional. If present it is
881 a bitwise OR of the following constants:
882
883 gdArc connect start & end points of arc with a rounded edge
884 gdChord connect start & end points of arc with a straight line
885 gdPie synonym for gdChord
886 gdNoFill outline the arc or chord
887 gdEdged connect beginning and ending of the arc to the center
888
889 gdArc and gdChord are mutually exclusive. gdChord just connects
890 the starting and ending angles with a straight line, while gdArc
891 produces a rounded edge. gdPie is a synonym for gdArc. gdNoFill
892 indicates that the arc or chord should be outlined, not filled.
893 gdEdged, used together with gdNoFill, indicates that the beginning
894 and ending angles should be connected to the center; this is a good
895 way to outline (rather than fill) a "pie slice."
896
897 Example:
898
899 $image->filledArc(100,100,50,50,0,90,$blue,gdEdged|gdNoFill);
900
901 $image->fill($x,$y,$color)
902 This method flood-fills regions with the specified color. The
903 color will spread through the image, starting at point (x,y), until
904 it is stopped by a pixel of a different color from the starting
905 pixel (this is similar to the "paintbucket" in many popular drawing
906 toys). You can specify a normal color, or the special color
907 gdTiled, to flood-fill with patterns.
908
909 Example:
910
911 # Draw a rectangle, and then make its interior blue
912 $myImage->rectangle(10,10,100,100,$black);
913 $myImage->fill(50,50,$blue);
914
915 $image->fillToBorder($x,$y,$bordercolor,$color)
916 Like "fill", this method flood-fills regions with the specified
917 color, starting at position (x,y). However, instead of stopping
918 when it hits a pixel of a different color than the starting pixel,
919 flooding will only stop when it hits the color specified by
920 bordercolor. You must specify a normal indexed color for the
921 bordercolor. However, you are free to use the gdTiled color for
922 the fill.
923
924 Example:
925
926 # This has the same effect as the previous example
927 $myImage->rectangle(10,10,100,100,$black);
928 $myImage->fillToBorder(50,50,$black,$blue);
929
930 Image Copying Commands
931 Two methods are provided for copying a rectangular region from one
932 image to another. One method copies a region without resizing it. The
933 other allows you to stretch the region during the copy operation.
934
935 With either of these methods it is important to know that the routines
936 will attempt to flesh out the destination image's color table to match
937 the colors that are being copied from the source. If the destination's
938 color table is already full, then the routines will attempt to find the
939 best match, with varying results.
940
941 $image->copy($sourceImage,$dstX,$dstY,$srcX,$srcY,$width,$height)
942 This is the simplest of the several copy operations, copying the
943 specified region from the source image to the destination image
944 (the one performing the method call). (srcX,srcY) specify the
945 upper left corner of a rectangle in the source image, and
946 (width,height) give the width and height of the region to copy.
947 (dstX,dstY) control where in the destination image to stamp the
948 copy. You can use the same image for both the source and the
949 destination, but the source and destination regions must not
950 overlap or strange things will happen.
951
952 Example:
953
954 $myImage = new GD::Image(100,100);
955 ... various drawing stuff ...
956 $srcImage = new GD::Image(50,50);
957 ... more drawing stuff ...
958 # copy a 25x25 pixel region from $srcImage to
959 # the rectangle starting at (10,10) in $myImage
960 $myImage->copy($srcImage,10,10,0,0,25,25);
961
962 $image->clone()
963 Make a copy of the image and return it as a new object. The new
964 image will look identical. However, it may differ in the size of
965 the color palette and other nonessential details.
966
967 Example:
968
969 $myImage = new GD::Image(100,100);
970 ... various drawing stuff ...
971 $copy = $myImage->clone;
972
973 $image->copyMerge($sourceImage,$dstX,$dstY,
974 $srcX,$srcY,$width,$height,$percent)
975
976 This copies the indicated rectangle from the source image to the
977 destination image, merging the colors to the extent specified by
978 percent (an integer between 0 and 100). Specifying 100% has the
979 same effect as copy() -- replacing the destination pixels with the
980 source image. This is most useful for highlighting an area by
981 merging in a solid rectangle.
982
983 Example:
984
985 $myImage = new GD::Image(100,100);
986 ... various drawing stuff ...
987 $redImage = new GD::Image(50,50);
988 ... more drawing stuff ...
989 # copy a 25x25 pixel region from $srcImage to
990 # the rectangle starting at (10,10) in $myImage, merging 50%
991 $myImage->copyMerge($srcImage,10,10,0,0,25,25,50);
992
993 $image->copyMergeGray($sourceImage,$dstX,$dstY,
994 $srcX,$srcY,$width,$height,$percent)
995
996 This is identical to copyMerge() except that it preserves the hue
997 of the source by converting all the pixels of the destination
998 rectangle to grayscale before merging.
999
1000 $image->copyResized($sourceImage,$dstX,$dstY,
1001 $srcX,$srcY,$destW,$destH,$srcW,$srcH)
1002
1003 This method is similar to copy() but allows you to choose different
1004 sizes for the source and destination rectangles. The source and
1005 destination rectangle's are specified independently by (srcW,srcH)
1006 and (destW,destH) respectively. copyResized() will stretch or
1007 shrink the image to accommodate the size requirements.
1008
1009 Example:
1010
1011 $myImage = new GD::Image(100,100);
1012 ... various drawing stuff ...
1013 $srcImage = new GD::Image(50,50);
1014 ... more drawing stuff ...
1015 # copy a 25x25 pixel region from $srcImage to
1016 # a larger rectangle starting at (10,10) in $myImage
1017 $myImage->copyResized($srcImage,10,10,0,0,50,50,25,25);
1018
1019 $image->copyResampled($sourceImage,$dstX,$dstY,
1020 $srcX,$srcY,$destW,$destH,$srcW,$srcH)
1021
1022 This method is similar to copyResized() but provides "smooth"
1023 copying from a large image to a smaller one, using a weighted
1024 average of the pixels of the source area rather than selecting one
1025 representative pixel. This method is identical to copyResized()
1026 when the destination image is a palette image.
1027
1028 $image->copyRotated($sourceImage,$dstX,$dstY,
1029 $srcX,$srcY,$width,$height,$angle)
1030
1031 Like copyResized() but the $angle argument specifies an arbitrary
1032 amount to rotate the image clockwise (in degrees). In addition,
1033 $dstX and $dstY species the center of the destination image, and
1034 not the top left corner.
1035
1036 $image->trueColorToPalette([$dither], [$colors])
1037 This method converts a truecolor image to a palette image. The code
1038 for this function was originally drawn from the Independent JPEG
1039 Group library code, which is excellent. The code has been modified
1040 to preserve as much alpha channel information as possible in the
1041 resulting palette, in addition to preserving colors as well as
1042 possible. This does not work as well as might be hoped. It is
1043 usually best to simply produce a truecolor output image instead,
1044 which guarantees the highest output quality. Both the dithering
1045 (0/1, default=0) and maximum number of colors used (<=256, default
1046 = gdMaxColors) can be specified.
1047
1048 $image = $sourceImage->createPaletteFromTrueColor([$dither], [$colors])
1049 Creates a new palette image from a truecolor image. Same as above,
1050 but returns a new image.
1051
1052 Don't use these function -- write real truecolor PNGs and JPEGs.
1053 The disk space gain of conversion to palette is not great (for
1054 small images it can be negative) and the quality loss is ugly.
1055
1056 $error = $image->colorMatch($otherimage)
1057 Bring the palette colors in $otherimage to be closer to truecolor
1058 $image. A negative return value is a failure.
1059
1060 -1 image must be True Color
1061 -2 otherimage must be indexed
1062 -3 the images are meant to be the same dimensions
1063 -4 At least 1 color in otherimage must be allocated
1064
1065 This method is only available with libgd >= 2.1.0
1066
1067 $image = $sourceImage->neuQuant($maxcolor=256,$samplefactor=5)
1068 Creates a new palette image from a truecolor image.
1069
1070 samplefactor The quantization precision between 1 (highest quality) and 10 (fastest).
1071 maxcolor The number of desired palette entries.
1072
1073 This is the same as createPaletteFromTrueColor with the
1074 quantization method GD_QUANT_NEUQUANT. This does not support
1075 dithering. This method is only available with libgd >= 2.1.0
1076
1077 Image Transformation Commands
1078 Gd provides these simple image transformations, non-interpolated.
1079
1080 $image = $sourceImage->copyRotate90()
1081 $image = $sourceImage->copyRotate180()
1082 $image = $sourceImage->copyRotate270()
1083 $image = $sourceImage->copyFlipHorizontal()
1084 $image = $sourceImage->copyFlipVertical()
1085 $image = $sourceImage->copyTranspose()
1086 $image = $sourceImage->copyReverseTranspose()
1087 These methods can be used to rotate, flip, or transpose an image.
1088 The result of the method is a copy of the image.
1089
1090 $image->rotate180()
1091 $image->flipHorizontal()
1092 $image->flipVertical()
1093 These methods are similar to the copy* versions, but instead modify
1094 the image in place.
1095
1096 Image Interpolation Methods
1097 Since libgd 2.1.0 there are better transformation methods, with these
1098 interpolation methods:
1099
1100 GD_BELL - Bell
1101 GD_BESSEL - Bessel
1102 GD_BILINEAR_FIXED - fixed point bilinear
1103 GD_BICUBIC - Bicubic
1104 GD_BICUBIC_FIXED - fixed point bicubic integer
1105 GD_BLACKMAN - Blackman
1106 GD_BOX - Box
1107 GD_BSPLINE - BSpline
1108 GD_CATMULLROM - Catmullrom
1109 GD_GAUSSIAN - Gaussian
1110 GD_GENERALIZED_CUBIC - Generalized cubic
1111 GD_HERMITE - Hermite
1112 GD_HAMMING - Hamming
1113 GD_HANNING - Hannig
1114 GD_MITCHELL - Mitchell
1115 GD_NEAREST_NEIGHBOUR - Nearest neighbour interpolation
1116 GD_POWER - Power
1117 GD_QUADRATIC - Quadratic
1118 GD_SINC - Sinc
1119 GD_TRIANGLE - Triangle
1120 GD_WEIGHTED4 - 4 pixels weighted bilinear interpolation
1121 GD_LINEAR - bilinear interpolation
1122
1123 $image->interpolationMethod( [$method] )
1124 Gets or sets the interpolation methods for all subsequent
1125 interpolations. See above for the valid values. Only available
1126 since libgd 2.2.0
1127
1128 $image->copyScaleInterpolated( width, height )
1129 Returns a copy, using interpolation.
1130
1131 $image->copyRotateInterpolated( angle, bgcolor )
1132 Returns a copy, using interpolation.
1133
1134 Image Filter Commands
1135 Gd also provides some common image filters, they modify the image in
1136 place and return TRUE if modified or FALSE if not. Most of them need
1137 libgd >= 2.1.0, with older versions those functions are undefined.
1138
1139 $ok = $image->scatter($sub, $plus)
1140 if $sub and $plus are 0, nothing is changed, TRUE is returned. if
1141 $sub >= $plus, nothing is changed, FALSE is returned. else random
1142 pixels are changed.
1143
1144 $ok = $image->scatterColor($sub, $plus, @colors)
1145 Similar to scatter, but using the given array of colors, i.e.
1146 palette indices.
1147
1148 $ok = $image->pixelate($blocksize, $mode)
1149 if $blocksize <= 0, nothing is changed, FALSE is returned. if
1150 $blocksize == 1, nothing is changed, TRUE is returned. else the
1151 following modes are observed:
1152 GD_PIXELATE_UPPERLEFT
1153 GD_PIXELATE_AVERAGE
1154
1155 $ok = $image->negate()
1156 $ok = $image->grayscale()
1157 $ok = $image->brightness($add)
1158 $add: -255..255
1159
1160 $ok = $image->contrast($contrast)
1161 $contrast: a double value. The contrast adjustment value. Negative
1162 values increase, positive values decrease the contrast. The larger
1163 the absolute value, the stronger the effect.
1164
1165 $ok = $image->color($red,$green,$blue,$alpha)
1166 Change channel values of an image.
1167
1168 $red - The value to add to the red channel of all pixels.
1169 $green - The value to add to the green channel of all pixels.
1170 $blue - The value to add to the blue channel of all pixels.
1171 $alpha - The value to add to the alpha channel of all pixels.
1172
1173 $ok = $image->selectiveBlur()
1174 $ok = $image->edgeDetectQuick()
1175 $ok = $image->gaussianBlur()
1176 $ok = $image->emboss()
1177 $ok = $image->meanRemoval()
1178 $ok = $image->smooth($weight)
1179 $image = $sourceImage->copyGaussianBlurred($radius, $sigma)
1180 $radius: int, the blur radius (*not* diameter--range is 2*radius +
1181 1) a radius, not a diameter so a radius of 2 (for example) will
1182 blur across a region 5 pixels across (2 to the center, 1 for the
1183 center itself and another 2 to the other edge).
1184
1185 $sigma: the sigma value or a value <= 0.0 to use the computed
1186 default. represents the "fatness" of the curve (lower == fatter).
1187
1188 The result is always truecolor.
1189
1190 Character and String Drawing
1191 GD allows you to draw characters and strings, either in normal
1192 horizontal orientation or rotated 90 degrees. These routines use a
1193 GD::Font object, described in more detail below. There are four built-
1194 in monospaced fonts, available in the global variables gdGiantFont,
1195 gdLargeFont, gdMediumBoldFont, gdSmallFont and gdTinyFont.
1196
1197 In addition, you can use the load() method to load GD-formatted bitmap
1198 font files at runtime. You can create these bitmap files from X11 BDF-
1199 format files using the bdf2gd.pl script, which should have been
1200 installed with GD (see the bdf_scripts directory if it wasn't). The
1201 format happens to be identical to the old-style MSDOS bitmap ".fnt"
1202 files, so you can use one of those directly if you happen to have one.
1203
1204 For writing proportional scalable fonts, GD offers the stringFT()
1205 method, which allows you to load and render any TrueType font on your
1206 system.
1207
1208 $image->string($font,$x,$y,$string,$color)
1209 This method draws a string starting at position (x,y) in the
1210 specified font and color. Your choices of fonts are gdSmallFont,
1211 gdMediumBoldFont, gdTinyFont, gdLargeFont and gdGiantFont.
1212
1213 Example:
1214
1215 $myImage->string(gdSmallFont,2,10,"Peachy Keen",$peach);
1216
1217 $image->stringUp($font,$x,$y,$string,$color)
1218 Just like the previous call, but draws the text rotated
1219 counterclockwise 90 degrees.
1220
1221 $image->char($font,$x,$y,$char,$color)
1222 $image->charUp($font,$x,$y,$char,$color)
1223 These methods draw single characters at position (x,y) in the
1224 specified font and color. They're carry-overs from the C
1225 interface, where there is a distinction between characters and
1226 strings. Perl is insensible to such subtle distinctions.
1227
1228 $font = GD::Font->load($fontfilepath)
1229 This method dynamically loads a font file, returning a font that
1230 you can use in subsequent calls to drawing methods. For example:
1231
1232 my $courier = GD::Font->load('./courierR12.fnt') or die "Can't load font";
1233 $image->string($courier,2,10,"Peachy Keen",$peach);
1234
1235 Font files must be in GD binary format, as described above.
1236
1237 @bounds =
1238 $image->stringFT($fgcolor,$fontname,$ptsize,$angle,$x,$y,$string)
1239 @bounds =
1240 GD::Image->stringFT($fgcolor,$fontname,$ptsize,$angle,$x,$y,$string)
1241 @bounds =
1242 $image->stringFT($fgcolor,$fontname,$ptsize,$angle,$x,$y,$string,\%options)
1243 This method uses TrueType to draw a scaled, antialiased string
1244 using the TrueType vector font of your choice. It requires that
1245 libgd to have been compiled with TrueType support, and for the
1246 appropriate TrueType font to be installed on your system.
1247
1248 The arguments are as follows:
1249
1250 fgcolor Color index to draw the string in
1251 fontname A path to the TrueType (.ttf) font file or a font pattern.
1252 ptsize The desired point size (may be fractional)
1253 angle The rotation angle, in radians (positive values rotate counter clockwise)
1254 x,y X and Y coordinates to start drawing the string
1255 string The string itself
1256
1257 If successful, the method returns an eight-element list giving the
1258 boundaries of the rendered string:
1259
1260 @bounds[0,1] Lower left corner (x,y)
1261 @bounds[2,3] Lower right corner (x,y)
1262 @bounds[4,5] Upper right corner (x,y)
1263 @bounds[6,7] Upper left corner (x,y)
1264
1265 In case of an error (such as the font not being available, or FT
1266 support not being available), the method returns an empty list and
1267 sets $@ to the error message.
1268
1269 The fontname argument is the name of the font, which can be a full
1270 pathname to a .ttf file, or if not the paths in $ENV{GDFONTPATH}
1271 will be searched or if empty the libgd compiled DEFAULT_FONTPATH.
1272 The TrueType extensions .ttf, .pfa, .pfb or .dfont can be omitted.
1273
1274 The string may contain UTF-8 sequences like: "À"
1275
1276 You may also call this method from the GD::Image class name, in
1277 which case it doesn't do any actual drawing, but returns the
1278 bounding box using an inexpensive operation. You can use this to
1279 perform layout operations prior to drawing.
1280
1281 Using a negative color index will disable antialiasing, as
1282 described in the libgd manual page at
1283 <http://www.boutell.com/gd/manual2.0.9.html#gdImageStringFT>.
1284
1285 An optional 8th argument allows you to pass a hashref of options to
1286 stringFT(). Several hashkeys are recognized: linespacing, charmap,
1287 resolution, and kerning.
1288
1289 The value of linespacing is supposed to be a multiple of the
1290 character height, so setting linespacing to 2.0 will result in
1291 double-spaced lines of text. However the current version of libgd
1292 (2.0.12) does not do this. Instead the linespacing seems to be
1293 double what is provided in this argument. So use a spacing of 0.5
1294 to get separation of exactly one line of text. In practice, a
1295 spacing of 0.6 seems to give nice results. Another thing to watch
1296 out for is that successive lines of text should be separated by the
1297 "\r\n" characters, not just "\n".
1298
1299 The value of charmap is one of "Unicode", "Shift_JIS" and "Big5".
1300 The interaction between Perl, Unicode and libgd is not clear to me,
1301 and you should experiment a bit if you want to use this feature.
1302
1303 The value of resolution is the vertical and horizontal resolution,
1304 in DPI, in the format "hdpi,vdpi". If present, the resolution will
1305 be passed to the Freetype rendering engine as a hint to improve the
1306 appearance of the rendered font.
1307
1308 The value of kerning is a flag. Set it to false to turn off the
1309 default kerning of text.
1310
1311 Example:
1312
1313 $gd->stringFT($black,'/c/windows/Fonts/pala.ttf',40,0,20,90,
1314 "hi there\r\nbye now",
1315 {linespacing=>0.6,
1316 charmap => 'Unicode',
1317 });
1318
1319 If GD was compiled with fontconfig support, and the fontconfig
1320 library is available on your system, then you can use a font name
1321 pattern instead of a path. Patterns are described in fontconfig
1322 and will look something like this "Times:italic". For backward
1323 compatibility, this feature is disabled by default. You must
1324 enable it by calling useFontConfig(1) prior to the stringFT() call.
1325
1326 $image->useFontConfig(1);
1327
1328 For backward compatibility with older versions of the FreeType
1329 library, the alias stringTTF() is also recognized.
1330
1331 $hasfontconfig = $image->useFontConfig($flag)
1332 Call useFontConfig() with a value of 1 in order to enable support
1333 for fontconfig font patterns (see stringFT). Regardless of the
1334 value of $flag, this method will return a true value if the
1335 fontconfig library is present, or false otherwise.
1336
1337 This method can also be called as a class method of GD::Image;
1338
1339 $result =
1340 $image->stringFTCircle($cx,$cy,$radius,$textRadius,$fillPortion,$font,$points,$top,$bottom,$fgcolor)
1341 This draws text in a circle. Currently (libgd 2.0.33) this function
1342 does not work for me, but the interface is provided for
1343 completeness. The call signature is somewhat complex. Here is an
1344 excerpt from the libgd manual page:
1345
1346 Draws the text strings specified by top and bottom on the image,
1347 curved along the edge of a circle of radius radius, with its center
1348 at cx and cy. top is written clockwise along the top; bottom is
1349 written counterclockwise along the bottom. textRadius determines
1350 the "height" of each character; if textRadius is 1/2 of radius,
1351 characters extend halfway from the edge to the center. fillPortion
1352 varies from 0 to 1.0, with useful values from about 0.4 to 0.9, and
1353 determines how much of the 180 degrees of arc assigned to each
1354 section of text is actually occupied by text; 0.9 looks better than
1355 1.0 which is rather crowded. font is a freetype font; see
1356 gdImageStringFT. points is passed to the freetype engine and has an
1357 effect on hinting; although the size of the text is determined by
1358 radius, textRadius, and fillPortion, you should pass a point size
1359 that "hints" appropriately -- if you know the text will be large,
1360 pass a large point size such as 24.0 to get the best results.
1361 fgcolor can be any color, and may have an alpha component, do
1362 blending, etc.
1363
1364 Returns a true value on success.
1365
1366 Alpha channels
1367 The alpha channel methods allow you to control the way drawings are
1368 processed according to the alpha channel. When true color is turned on,
1369 colors are encoded as four bytes, in which the last three bytes are the
1370 RGB color values, and the first byte is the alpha channel. Therefore
1371 the hexadecimal representation of a non transparent RGB color will be:
1372 C=0x00(rr)(bb)(bb)
1373
1374 When alpha blending is turned on, you can use the first byte of the
1375 color to control the transparency, meaning that a rectangle painted
1376 with color 0x00(rr)(bb)(bb) will be opaque, and another one painted
1377 with 0x7f(rr)(gg)(bb) will be transparent. The Alpha value must be >= 0
1378 and <= 0x7f.
1379
1380 $image->alphaBlending($integer)
1381 The alphaBlending() method allows for two different modes of
1382 drawing on truecolor images. In blending mode, which is on by
1383 default (libgd 2.0.2 and above), the alpha channel component of the
1384 color supplied to all drawing functions, such as "setPixel",
1385 determines how much of the underlying color should be allowed to
1386 shine through. As a result, GD automatically blends the existing
1387 color at that point with the drawing color, and stores the result
1388 in the image. The resulting pixel is opaque. In non-blending mode,
1389 the drawing color is copied literally with its alpha channel
1390 information, replacing the destination pixel. Blending mode is not
1391 available when drawing on palette images.
1392
1393 Pass a value of 1 for blending mode, and 0 for non-blending mode.
1394
1395 $image->saveAlpha($saveAlpha)
1396 By default, GD (libgd 2.0.2 and above) does not attempt to save
1397 full alpha channel information (as opposed to single-color
1398 transparency) when saving PNG images. (PNG is currently the only
1399 output format supported by gd which can accommodate alpha channel
1400 information.) This saves space in the output file. If you wish to
1401 create an image with alpha channel information for use with tools
1402 that support it, call saveAlpha(1) to turn on saving of such
1403 information, and call alphaBlending(0) to turn off alpha blending
1404 within the library so that alpha channel information is actually
1405 stored in the image rather than being composited immediately at the
1406 time that drawing functions are invoked.
1407
1408 Miscellaneous Image Methods
1409 These are various utility methods that are useful in some
1410 circumstances.
1411
1412 $image->interlaced([$flag])
1413 This method sets or queries the image's interlaced setting.
1414 Interlace produces a cool venetian blinds effect on certain
1415 viewers. Provide a true parameter to set the interlace attribute.
1416 Provide undef to disable it. Call the method without parameters to
1417 find out the current setting.
1418
1419 ($width,$height) = $image->getBounds()
1420 This method will return a two-member list containing the width and
1421 height of the image. You query but not change the size of the
1422 image once it's created.
1423
1424 $width = $image->width
1425 $height = $image->height
1426 Return the width and height of the image, respectively.
1427
1428 $is_truecolor = $image->isTrueColor()
1429 This method will return a Boolean representing whether the image is
1430 true color or not.
1431
1432 $flag = $image1->compare($image2)
1433 Compare two images and return a bitmap describing the differences
1434 found, if any. The return value must be logically AND'ed with one
1435 or more constants in order to determine the differences. The
1436 following constants are available:
1437
1438 GD_CMP_IMAGE The two images look different
1439 GD_CMP_NUM_COLORS The two images have different numbers of colors
1440 GD_CMP_COLOR The two images' palettes differ
1441 GD_CMP_SIZE_X The two images differ in the horizontal dimension
1442 GD_CMP_SIZE_Y The two images differ in the vertical dimension
1443 GD_CMP_TRANSPARENT The two images have different transparency
1444 GD_CMP_BACKGROUND The two images have different background colors
1445 GD_CMP_INTERLACE The two images differ in their interlace
1446 GD_CMP_TRUECOLOR The two images are not both true color
1447
1448 The most important of these is GD_CMP_IMAGE, which will tell you
1449 whether the two images will look different, ignoring differences in
1450 the order of colors in the color palette and other invisible
1451 changes. The constants are not imported by default, but must be
1452 imported individually or by importing the :cmp tag. Example:
1453
1454 use GD qw(:DEFAULT :cmp);
1455 # get $image1 from somewhere
1456 # get $image2 from somewhere
1457 if ($image1->compare($image2) & GD_CMP_IMAGE) {
1458 warn "images differ!";
1459 }
1460
1461 $image->clip($x1,$y1,$x2,$y2)
1462 ($x1,$y1,$x2,$y2) = $image->clip
1463 Set or get the clipping rectangle. When the clipping rectangle is
1464 set, all drawing will be clipped to occur within this rectangle.
1465 The clipping rectangle is initially set to be equal to the
1466 boundaries of the whole image. Change it by calling clip() with the
1467 coordinates of the new clipping rectangle. Calling clip() without
1468 any arguments will return the current clipping rectangle.
1469
1470 $flag = $image->boundsSafe($x,$y)
1471 The boundsSafe() method will return true if the point indicated by
1472 ($x,$y) is within the clipping rectangle, or false if it is not.
1473 If the clipping rectangle has not been set, then it will return
1474 true if the point lies within the image boundaries.
1475
1476 Grouping Methods
1477 GD does not support grouping of objects, but GD::SVG does. In that
1478 subclass, the following methods declare new groups of graphical
1479 objects:
1480
1481 $image->startGroup([$id,\%style])
1482 $image->endGroup()
1483 $group = $image->newGroup
1484 See GD::SVG for information.
1485
1487 A few primitive polygon creation and manipulation methods are provided.
1488 They aren't part of the Gd library, but I thought they might be handy
1489 to have around (they're borrowed from my qd.pl Quickdraw library).
1490 Also see GD::Polyline.
1491
1492 $poly = GD::Polygon->new
1493 Create an empty polygon with no vertices.
1494
1495 $poly = new GD::Polygon;
1496
1497 $poly->addPt($x,$y)
1498 Add point (x,y) to the polygon.
1499
1500 $poly->addPt(0,0);
1501 $poly->addPt(0,50);
1502 $poly->addPt(25,25);
1503 $myImage->fillPoly($poly,$blue);
1504
1505 ($x,$y) = $poly->getPt($index)
1506 Retrieve the point at the specified vertex.
1507
1508 ($x,$y) = $poly->getPt(2);
1509
1510 $poly->setPt($index,$x,$y)
1511 Change the value of an already existing vertex. It is an error to
1512 set a vertex that isn't already defined.
1513
1514 $poly->setPt(2,100,100);
1515
1516 ($x,$y) = $poly->deletePt($index)
1517 Delete the specified vertex, returning its value.
1518
1519 ($x,$y) = $poly->deletePt(1);
1520
1521 $poly->clear()
1522 Delete all vertices, restoring the polygon to its initial empty
1523 state.
1524
1525 $poly->toPt($dx,$dy)
1526 Draw from current vertex to a new vertex, using relative (dx,dy)
1527 coordinates. If this is the first point, act like addPt().
1528
1529 $poly->addPt(0,0);
1530 $poly->toPt(0,50);
1531 $poly->toPt(25,-25);
1532 $myImage->fillPoly($poly,$blue);
1533
1534 $vertex_count = $poly->length
1535 Return the number of vertices in the polygon.
1536
1537 $points = $poly->length;
1538
1539 @vertices = $poly->vertices
1540 Return a list of all the vertices in the polygon object. Each
1541 member of the list is a reference to an (x,y) array.
1542
1543 @vertices = $poly->vertices;
1544 foreach $v (@vertices)
1545 print join(",",@$v),"\n";
1546 }
1547
1548 @rect = $poly->bounds
1549 Return the smallest rectangle that completely encloses the polygon.
1550 The return value is an array containing the (left,top,right,bottom)
1551 of the rectangle.
1552
1553 ($left,$top,$right,$bottom) = $poly->bounds;
1554
1555 $poly->offset($dx,$dy)
1556 Offset all the vertices of the polygon by the specified horizontal
1557 (dh) and vertical (dy) amounts. Positive numbers move the polygon
1558 down and to the right.
1559
1560 $poly->offset(10,30);
1561
1562 $poly->map($srcL,$srcT,$srcR,$srcB,$destL,$dstT,$dstR,$dstB)
1563 Map the polygon from a source rectangle to an equivalent position in
1564 a destination rectangle, moving it and resizing it as necessary.
1565 See polys.pl for an example of how this works. Both the source and
1566 destination rectangles are given in (left,top,right,bottom)
1567 coordinates. For convenience, you can use the polygon's own
1568 bounding box as the source rectangle.
1569
1570 # Make the polygon really tall
1571 $poly->map($poly->bounds,0,0,50,200);
1572
1573 $poly->scale($sx,$sy)
1574 Scale each vertex of the polygon by the X and Y factors indicated by
1575 sx and sy. For example scale(2,2) will make the polygon twice as
1576 large. For best results, move the center of the polygon to position
1577 (0,0) before you scale, then move it back to its previous position.
1578
1579 $poly->transform($sx,$rx,$sy,$ry,$tx,$ty)
1580 Run each vertex of the polygon through a transformation matrix,
1581 where sx and sy are the X and Y scaling factors, rx and ry are the X
1582 and Y rotation factors, and tx and ty are X and Y offsets. See the
1583 Adobe PostScript Reference, page 154 for a full explanation, or
1584 experiment.
1585
1586 GD::Polyline
1587 Please see GD::Polyline for information on creating open polygons and
1588 splines.
1589
1591 The libgd library (used by the Perl GD library) has built-in support
1592 for about half a dozen fonts, which were converted from public-domain X
1593 Windows fonts. For more fonts, compile libgd with TrueType support and
1594 use the stringFT() call.
1595
1596 If you wish to add more built-in fonts, the directory bdf_scripts
1597 contains two contributed utilities that may help you convert X-Windows
1598 BDF-format fonts into the format that libgd uses internally. However
1599 these scripts were written for earlier versions of GD which included
1600 its own mini-gd library. These scripts will have to be adapted for use
1601 with libgd, and the libgd library itself will have to be recompiled and
1602 linked! Please do not contact me for help with these scripts: they are
1603 unsupported.
1604
1605 Each of these fonts is available both as an imported global (e.g.
1606 gdSmallFont) and as a package method (e.g. GD::Font->Small).
1607
1608 gdSmallFont
1609 GD::Font->Small
1610 This is the basic small font, "borrowed" from a well known public
1611 domain 6x12 font.
1612
1613 gdLargeFont
1614 GD::Font->Large
1615 This is the basic large font, "borrowed" from a well known public
1616 domain 8x16 font.
1617
1618 gdMediumBoldFont
1619 GD::Font->MediumBold
1620 This is a bold font intermediate in size between the small and
1621 large fonts, borrowed from a public domain 7x13 font;
1622
1623 gdTinyFont
1624 GD::Font->Tiny
1625 This is a tiny, almost unreadable font, 5x8 pixels wide.
1626
1627 gdGiantFont
1628 GD::Font->Giant
1629 This is a 9x15 bold font converted by Jan Pazdziora from a sans
1630 serif X11 font.
1631
1632 $font->nchars
1633 This returns the number of characters in the font.
1634
1635 print "The large font contains ",gdLargeFont->nchars," characters\n";
1636
1637 $font->offset
1638 This returns the ASCII value of the first character in the font
1639
1640 $width = $font->width
1641 $height = $font->height
1642 "height"
1643 These return the width and height of the font.
1644
1645 ($w,$h) = (gdLargeFont->width,gdLargeFont->height);
1646
1648 GD::LIBGD_VERSION
1649 Returns a number of the libgd VERSION, like 2.0204, 2.0033 or 2.01.
1650
1651 GD::VERSION_STRING
1652 Returns the string of the libgd VERSION, like "2.2.4".
1653
1654 GD::constant
1655
1657 libgd, the C-language version of gd, can be obtained at URL
1658 http://libgd.org/ Directions for installing and using it can be found
1659 at that site. Please do not contact me for help with libgd.
1660
1662 The GD.pm interface is copyright 1995-2010, Lincoln D. Stein. This
1663 package and its accompanying libraries is free software; you can
1664 redistribute it and/or modify it under the terms of the GPL (either
1665 version 1, or at your option, any later version) or the Artistic
1666 License 2.0. Refer to LICENSE for the full license text. package for
1667 details.
1668
1669 The latest versions of GD.pm are available at
1670
1671 https://github.com/lstein/Perl-GD
1672
1674 GD::Polyline, GD::SVG, GD::Simple, Image::Magick
1675
1676
1677
1678perl v5.28.0 2018-08-26 GD(3)