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