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