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