GD(3pm) | User Contributed Perl Documentation | GD(3pm) |
GD.pm - Interface to Gd Graphics Library
use GD; # create a new image $im = GD::Image->new(100,100); # allocate some colors $white = $im->colorAllocate(255,255,255); $black = $im->colorAllocate(0,0,0); $red = $im->colorAllocate(255,0,0); $blue = $im->colorAllocate(0,0,255); # make the background transparent and interlaced $im->transparent($white); $im->interlaced('true'); # Put a black frame around the picture $im->rectangle(0,0,99,99,$black); # Draw a blue oval $im->arc(50,50,95,75,0,360,$blue); # And fill it with red $im->fill(50,50,$red); # make sure we are writing to a binary stream binmode STDOUT; # Convert the image to PNG and print it on standard output print $im->png;
GD.pm is a Perl interface to Thomas Boutell's gd graphics library (version 2.01 or higher; see below). GD allows you to create color drawings using a large number of graphics primitives, and emit the drawings as PNG files.
GD defines the following four classes:
A Simple Example:
#!/usr/bin/perl use GD; # create a new image $im = GD::Image->new(100,100); # allocate some colors $white = $im->colorAllocate(255,255,255); $black = $im->colorAllocate(0,0,0); $red = $im->colorAllocate(255,0,0); $blue = $im->colorAllocate(0,0,255); # make the background transparent and interlaced $im->transparent($white); $im->interlaced('true'); # Put a black frame around the picture $im->rectangle(0,0,99,99,$black); # Draw a blue oval $im->arc(50,50,95,75,0,360,$blue); # And fill it with red $im->fill(50,50,$red); # make sure we are writing to a binary stream binmode STDOUT; # Convert the image to PNG and print it on standard output print $im->png;
Notes:
See GD::Image for the current list of supported Image formats.
The following class methods allow you to create new GD::Image objects.
$myImage = GD::Image->new(100,100) || die;
This will create an image that is 100 x 100 pixels wide. If you don't specify the dimensions, a default of 64 x 64 will be chosen.
The optional third argument, $truecolor, tells new() to create a truecolor GD::Image object. Truecolor images have 24 bits of color data (eight bits each in the red, green and blue channels respectively), allowing for precise photograph-quality color usage. If not specified, the image will use an 8-bit palette for compatibility with older versions of libgd.
Alternatively, you may create a GD::Image object based on an existing image by providing an open filehandle, a filename, or the image data itself. The image formats automatically recognized and accepted are: GIF, PNG, JPEG, XBM, XPM, GD2, TIFF, WEBP, HEIF or AVIF. Other formats, including WBMP, and GD version 1, cannot be recognized automatically at this time.
If something goes wrong (e.g. insufficient memory), this call will return undef.
GD::Image->trueColor(1);
before creating new images. To switch back to palette based by default, use:
GD::Image->trueColor(0);
You may use any of the following as the argument:
1) a simple filehandle, such as STDIN 2) a filehandle glob, such as *PNG 3) a reference to a glob, such as \*PNG 4) an IO::Handle object 5) the pathname of a file
In the latter case, newFromPng() will attempt to open the file for you and read the PNG information from it.
Example1: open (PNG,"barnswallow.png") || die; $myImage = GD::Image->newFromPng(\*PNG) || die; close PNG; Example2: $myImage = GD::Image->newFromPng('barnswallow.png');
To get information about the size and color usage of the information, you can call the image query methods described below. Images created by reading PNG images will be truecolor if the image file itself is truecolor. To force the image to be palette-based, pass a value of 0 in the optional $truecolor argument.
The newFromPngData() method will create a new GD::Image initialized with the PNG format data contained in $data.
Images created by reading JPEG images will always be truecolor. To force the image to be palette-based, pass a value of 0 in the optional $truecolor argument.
Images created from GIFs are always 8-bit palette images. To convert to truecolor, you must create a truecolor image and then perform a copy.
open (XBM,"coredump.xbm") || die; $myImage = GD::Image->newFromXbm(\*XBM) || die; close XBM;
There is no newFromXbmData() function, because there is no corresponding function in the gd library.
open (BMP,"coredump.bmp") || die; $myImage = GD::Image->newFromWBMP(\*BMP) || die; close BMP;
There is no newFromWBMPData() function, because there is no corresponding function in the gd library.
These methods initialize a GD::Image from a Gd file, filehandle, or data. Gd is Tom Boutell's disk-based storage format, intended for the rare case when you need to read and write the image to disk quickly. It's not intended for regular use, because, unlike PNG or JPEG, no image compression is performed and these files can become BIG.
$myImage = GD::Image->newFromGd("godzilla.gd") || die; close GDF;
This works in exactly the same way as "newFromGd()" and newFromGdData, but use the new compressed GD2 image format.
open (GDF,"godzilla.gd2") || die; $myImage = GD::Image->newFromGd2Part(\*GDF,10,20,100,100) || die; close GDF;
This reads a 100x100 square portion of the image starting from position (10,20).
$myImage = GD::Image->newFromXpm('earth.xpm') || die;
This function is only available if libgd was compiled with XPM support.
NOTE: The libgd library is unable to read certain XPM files, returning an all-black image instead.
Assuming LibGD is compiled with support for these image types, the following extensions are supported:
.gif .gd, .gd2 .wbmp .bmp .xbm .tga .png .jpg, .jpeg .tiff, .tif .webp .heic, .heix .avif .xpm
Filenames are parsed case-insensitively. .avifs is not yet suppurted upstream in libavif.
Once a GD::Image object is created, you can draw with it, copy it, and merge two images. When you are finished manipulating the object, you can convert it into a standard image file format to output or save to a file.
The following methods convert the internal drawing format into standard output file formats.
$png_data = $myImage->png; open (DISPLAY,"| display -") || die; binmode DISPLAY; print DISPLAY $png_data; close DISPLAY;
Note the use of "binmode()". This is crucial for portability to DOSish platforms.
The optional $compression_level argument controls the amount of compression to apply to the output PNG image. Values range from 0-9, where 0 means no compression (largest files, highest quality) and 9 means maximum compression (smallest files, worst quality). A compression level of -1 uses the default compression level selected when zlib was compiled on your system, and is the same as calling png() with no argument. Be careful not to confuse this argument with the jpeg() quality argument, which ranges from 0-100 and has the opposite meaning from compression (higher numbers give higher quality).
A typical sequence will look like this:
my $gifdata = $image->gifanimbegin; $gifdata .= $image->gifanimadd; # first frame for (1..100) { # make a frame of right size my $frame = GD::Image->new($image->getBounds); add_frame_data($frame); # add the data for this frame $gifdata .= $frame->gifanimadd; # add frame } $gifdata .= $image->gifanimend; # finish the animated GIF print $gifdata; # write animated gif to STDOUT
If you do not wish to store the data in memory, you can print it to stdout or a file.
The image that you call gifanimbegin on is used to set the image size, color resolution and color map. If argument $GlobalCM is 1, the image color map becomes the GIF89a global color map. If $Loops is given and >= 0, the NETSCAPE2.0 application extension is created, with looping count. Looping count 0 means forever.
binmode MYOUTFILE; print MYOUTFILE $myImage->gd;
File type is determined by the extension of the file name. See "supportsFiletype" for an overview of the parsing.
For file types that require extra arguments, "_file" attempts to use sane defaults:
C<gdImageGd2> chunk size = 0, compression is enabled. C<gdImageJpeg> quality = -1 (i.e. the reasonable default) C<gdImageWBMP> foreground is the darkest available color C<gdImageWEBP> quality default C<gdImageHEIF> quality default, codes = HEVC, chroma = 444 C<gdImageAVIF> quality default, speed = 6
Everything else is called with the two-argument function and so will use the default values.
"_file" and the underlying libgd "gdImageFile" has some rudimentary error detection and will return FALSE (0) if a detectable error occurred. However, the image loaders do not normally return their error status so a result of TRUE (1) does **not** mean the file was saved successfully.
These methods allow you to control and manipulate the GD::Image color table for palette, non-truecolor images.
If no colors are allocated, then this function returns -1.
Example:
$black = $myImage->colorAllocate(0,0,0); #background color $white = $myImage->colorAllocate(255,255,255); $peachpuff = $myImage->colorAllocate(255,218,185);
Example:
$myImage->colorDeallocate($peachpuff); $peachy = $myImage->colorAllocate(255,210,185);
Example:
$apricot = $myImage->colorClosest(255,200,180);
Example:
$apricot = $myImage->colorClosestAlpha(255,200,180,0);
If no colors have yet been allocated, then this call returns -1.
Example:
$mostred = $myImage->colorClosestHWB(255,0,0);
$rosey = $myImage->colorExact(255,100,80); warn "Everything's coming up roses.\n" if $rosey >= 0;
$rosey = $myImage->colorExactAlpha(255,100,80,0); warn "Everything's coming up roses.\n" if $rosey >= 0;
$rosey = $myImage->colorResolve(255,100,80); warn "Everything's coming up roses.\n" if $rosey >= 0;
$rosey = $myImage->colorResolveAlpha(255,100,80,0); warn "Everything's coming up roses.\n" if $rosey >= 0;
$maxColors = $myImage->colorsTotal;
In the case of a TrueColor image, this call will return undef.
Example:
$index = $myImage->getPixel(20,100); ($r,$g,$b) = $myImage->rgb($index);
Example:
@RGB = $myImage->rgb($peachy);
Example:
@RGB = $myImage->rgb($peachy);
If you call this method without any parameters, it will return the current index of the transparent color, or -1 if none.
Example:
open(PNG,"test.png"); $im = GD::Image->newFromPng(PNG); $white = $im->colorClosest(255,255,255); # find white $im->transparent($white); binmode STDOUT; print $im->png;
GD implements a number of special colors that can be used to achieve special effects. They are constants defined in the GD:: namespace, but automatically exported into your namespace when the GD module is loaded.
To make a brushed line, you must create or load the brush first, then assign it to the image using setBrush(). You can then draw in that with that brush using the gdBrushed special color. It's often useful to set the background of the brush to transparent so that the non-colored parts don't overwrite other parts of your image.
Example:
# Create a brush at an angle $diagonal_brush = GD::Image->new(5,5); $white = $diagonal_brush->colorAllocate(255,255,255); $black = $diagonal_brush->colorAllocate(0,0,0); $diagonal_brush->transparent($white); $diagonal_brush->line(0,4,4,0,$black); # NE diagonal # Set the brush $myImage->setBrush($diagonal_brush); # Draw a circle using the brush $myImage->arc(50,50,25,25,0,360,gdBrushed);
Example:
# Set a style consisting of 4 pixels of yellow, # 4 pixels of blue, and a 2 pixel gap $myImage->setStyle($yellow,$yellow,$yellow,$yellow, $blue,$blue,$blue,$blue, gdTransparent,gdTransparent); $myImage->arc(50,50,25,25,0,360,gdStyled);
To combine the "gdStyled" and "gdBrushed" behaviors, you can specify "gdStyledBrushed". In this case, a pixel from the current brush pattern is rendered wherever the color specified in setStyle() is neither gdTransparent nor 0.
setAntiAliased() is used to specify the actual foreground color to be used when drawing antialiased lines. You may set any color to be the foreground, however as of libgd version 2.0.12 an alpha channel component is not supported.
Antialiased lines can be drawn on both truecolor and palette-based images. However, attempts to draw antialiased lines on highly complex palette-based backgrounds may not give satisfactory results, due to the limited number of colors available in the palette. Antialiased line-drawing on simple backgrounds should work well with palette-based images; otherwise create or fetch a truecolor image instead. When using palette-based images, be sure to allocate a broad spectrum of colors in order to have sufficient colors for the antialiasing to use.
Once turned on, you can turn this feature off by calling setAntiAliasedDontBlend() with a second argument of 0:
$image->setAntiAliasedDontBlend($color,0);
These methods allow you to draw lines, rectangles, and ellipses, as well as to perform various special operations like flood-fill.
Example:
# This assumes $peach already allocated $myImage->setPixel(50,50,$peach);
Example:
# Draw a diagonal line using the currently defined # paintbrush pattern. $myImage->line(0,0,150,150,gdBrushed);
This draws a dashed line from (x1,y1) to (x2,y2) in the specified color. A more powerful way to generate arbitrary dashed and dotted lines is to use the setStyle() method described below and to draw with the special color gdStyled.
Example:
$myImage->dashedLine(0,0,150,150,$blue);
Example:
$myImage->rectangle(10,10,100,100,$rose);
Example:
# read in a fill pattern and set it $tile = GD::Image->newFromPng('happyface.png'); $myImage->setTile($tile); # draw the rectangle, filling it with the pattern $myImage->filledRectangle(10,10,150,200,gdTiled);
Example:
$poly = GD::Polygon->new; $poly->addPt(50,0); $poly->addPt(99,99); $poly->addPt(0,99); $myImage->openPolygon($poly,$blue);
You need libgd 2.0.33 or higher to use this feature.
Example:
$poly = GD::Polygon->new; $poly->addPt(50,0); $poly->addPt(99,99); $poly->addPt(0,99); $myImage->unclosedPolygon($poly,$blue);
Example:
# make a polygon $poly = GD::Polygon->new; $poly->addPt(50,0); $poly->addPt(99,99); $poly->addPt(0,99); # draw the polygon, filling it with a color $myImage->filledPolygon($poly,$peachpuff);
You can specify a normal color or one of the special colors gdBrushed, gdStyled, or gdStyledBrushed.
Example:
# draw a semicircle centered at 100,100 $myImage->arc(100,100,50,50,0,180,$blue);
gdArc connect start & end points of arc with a rounded edge gdChord connect start & end points of arc with a straight line gdPie synonym for gdChord gdNoFill outline the arc or chord gdEdged connect beginning and ending of the arc to the center
gdArc and gdChord are mutually exclusive. gdChord just connects the starting and ending angles with a straight line, while gdArc produces a rounded edge. gdPie is a synonym for gdArc. gdNoFill indicates that the arc or chord should be outlined, not filled. gdEdged, used together with gdNoFill, indicates that the beginning and ending angles should be connected to the center; this is a good way to outline (rather than fill) a "pie slice."
Example:
$image->filledArc(100,100,50,50,0,90,$blue,gdEdged|gdNoFill);
Example:
# Draw a rectangle, and then make its interior blue $myImage->rectangle(10,10,100,100,$black); $myImage->fill(50,50,$blue);
Example:
# This has the same effect as the previous example $myImage->rectangle(10,10,100,100,$black); $myImage->fillToBorder(50,50,$black,$blue);
Two methods are provided for copying a rectangular region from one image to another. One method copies a region without resizing it. The other allows you to stretch the region during the copy operation.
With either of these methods it is important to know that the routines will attempt to flesh out the destination image's color table to match the colors that are being copied from the source. If the destination's color table is already full, then the routines will attempt to find the best match, with varying results.
Example:
$myImage = GD::Image->new(100,100); ... various drawing stuff ... $srcImage = GD::Image->new(50,50); ... more drawing stuff ... # copy a 25x25 pixel region from $srcImage to # the rectangle starting at (10,10) in $myImage $myImage->copy($srcImage,10,10,0,0,25,25);
Example:
$myImage = GD::Image->new(100,100); ... various drawing stuff ... $copy = $myImage->clone;
This copies the indicated rectangle from the source image to the destination image, merging the colors to the extent specified by percent (an integer between 0 and 100). Specifying 100% has the same effect as copy() -- replacing the destination pixels with the source image. This is most useful for highlighting an area by merging in a solid rectangle.
Example:
$myImage = GD::Image->new(100,100); ... various drawing stuff ... $redImage = GD::Image->new(50,50); ... more drawing stuff ... # copy a 25x25 pixel region from $srcImage to # the rectangle starting at (10,10) in $myImage, merging 50% $myImage->copyMerge($srcImage,10,10,0,0,25,25,50);
This is identical to copyMerge() except that it preserves the hue of the source by converting all the pixels of the destination rectangle to grayscale before merging.
This method is similar to copy() but allows you to choose different sizes for the source and destination rectangles. The source and destination rectangle's are specified independently by (srcW,srcH) and (destW,destH) respectively. copyResized() will stretch or shrink the image to accommodate the size requirements.
Example:
$myImage = GD::Image->new(100,100); ... various drawing stuff ... $srcImage = GD::Image->new(50,50); ... more drawing stuff ... # copy a 25x25 pixel region from $srcImage to # a larger rectangle starting at (10,10) in $myImage $myImage->copyResized($srcImage,10,10,0,0,50,50,25,25);
This method is similar to copyResized() but provides "smooth" copying from a large image to a smaller one, using a weighted average of the pixels of the source area rather than selecting one representative pixel. This method is identical to copyResized() when the destination image is a palette image.
Like copyResized() but the $angle argument specifies an arbitrary amount to rotate the image counter clockwise (in degrees). In addition, $dstX and $dstY species the center of the destination image, and not the top left corner.
Don't use these function -- write real truecolor PNGs and JPEGs. The disk space gain of conversion to palette is not great (for small images it can be negative) and the quality loss is ugly.
-1 image must be True Color -2 otherimage must be indexed -3 the images are meant to be the same dimensions -4 At least 1 color in otherimage must be allocated
This method is only available with libgd >= 2.1.0
This is the same as createPaletteFromTrueColor with the quantization method GD_QUANT_NEUQUANT. This does not support dithering. This method is only available with libgd >= 2.1.0
Gd provides these simple image transformations, non-interpolated.
Since libgd 2.1.0 there are better transformation methods, with these interpolation methods:
GD_BELL - Bell GD_BESSEL - Bessel GD_BILINEAR_FIXED - fixed point bilinear GD_BICUBIC - Bicubic GD_BICUBIC_FIXED - fixed point bicubic integer GD_BLACKMAN - Blackman GD_BOX - Box GD_BSPLINE - BSpline GD_CATMULLROM - Catmullrom GD_GAUSSIAN - Gaussian GD_GENERALIZED_CUBIC - Generalized cubic GD_HERMITE - Hermite GD_HAMMING - Hamming GD_HANNING - Hannig GD_MITCHELL - Mitchell GD_NEAREST_NEIGHBOUR - Nearest neighbour interpolation GD_POWER - Power GD_QUADRATIC - Quadratic GD_SINC - Sinc GD_TRIANGLE - Triangle GD_WEIGHTED4 - 4 pixels weighted bilinear interpolation GD_LINEAR - bilinear interpolation
Gd also provides some common image filters, they modify the image in place and return TRUE if modified or FALSE if not. Most of them need libgd >= 2.1.0, with older versions those functions are undefined.
$red - The value to add to the red channel of all pixels. $green - The value to add to the green channel of all pixels. $blue - The value to add to the blue channel of all pixels. $alpha - The value to add to the alpha channel of all pixels.
$sigma: the sigma value or a value <= 0.0 to use the computed default. represents the "fatness" of the curve (lower == fatter).
The result is always truecolor.
GD allows you to draw characters and strings, either in normal horizontal orientation or rotated 90 degrees. These routines use a GD::Font object, described in more detail below. There are four built-in monospaced fonts, available in the global variables gdGiantFont, gdLargeFont, gdMediumBoldFont, gdSmallFont and gdTinyFont.
In addition, you can use the load() method to load GD-formatted bitmap font files at runtime. You can create these bitmap files from X11 BDF-format files using the bdf2gd.pl script, which should have been installed with GD (see the bdf_scripts directory if it wasn't). The format happens to be identical to the old-style MSDOS bitmap ".fnt" files, so you can use one of those directly if you happen to have one.
For writing proportional scalable fonts, GD offers the stringFT() method, which allows you to load and render any TrueType font on your system.
Example:
$myImage->string(gdSmallFont,2,10,"Peachy Keen",$peach);
my $courier = GD::Font->load('./courierR12.fnt') or die "Can't load font"; $image->string($courier,2,10,"Peachy Keen",$peach);
Font files must be in GD binary format, as described above.
The arguments are as follows:
fgcolor Color index to draw the string in fontname A path to the TrueType (.ttf) font file or a font pattern. ptsize The desired point size (may be fractional) angle The rotation angle, in radians (positive values rotate counter clockwise) x,y X and Y coordinates to start drawing the string string The string itself
If successful, the method returns an eight-element list giving the boundaries of the rendered string:
@bounds[0,1] Lower left corner (x,y) @bounds[2,3] Lower right corner (x,y) @bounds[4,5] Upper right corner (x,y) @bounds[6,7] Upper left corner (x,y)
In case of an error (such as the font not being available, or FT support not being available), the method returns an empty list and sets $@ to the error message.
The fontname argument is the name of the font, which can be a full pathname to a .ttf file, or if not the paths in $ENV{GDFONTPATH} will be searched or if empty the libgd compiled DEFAULT_FONTPATH. The TrueType extensions .ttf, .pfa, .pfb or .dfont can be omitted.
The string may contain UTF-8 sequences like: "À"
You may also call this method from the GD::Image class name, in which case it doesn't do any actual drawing, but returns the bounding box using an inexpensive operation. You can use this to perform layout operations prior to drawing.
Using a negative color index will disable antialiasing, as described in the libgd manual page at <http://www.boutell.com/gd/manual2.0.9.html#gdImageStringFT>.
An optional 8th argument allows you to pass a hashref of options to stringFT(). Several hashkeys are recognized: linespacing, charmap, resolution, and kerning.
The value of linespacing is supposed to be a multiple of the character height, so setting linespacing to 2.0 will result in double-spaced lines of text. However the current version of libgd (2.0.12) does not do this. Instead the linespacing seems to be double what is provided in this argument. So use a spacing of 0.5 to get separation of exactly one line of text. In practice, a spacing of 0.6 seems to give nice results. Another thing to watch out for is that successive lines of text should be separated by the "\r\n" characters, not just "\n".
The value of charmap is one of "Unicode", "Shift_JIS" and "Big5". The interaction between Perl, Unicode and libgd is not clear to me, and you should experiment a bit if you want to use this feature.
The value of resolution is the vertical and horizontal resolution, in DPI, in the format "hdpi,vdpi". If present, the resolution will be passed to the Freetype rendering engine as a hint to improve the appearance of the rendered font.
The value of kerning is a flag. Set it to false to turn off the default kerning of text.
Example:
$gd->stringFT($black,'/c/windows/Fonts/pala.ttf',40,0,20,90, "hi there\r\nbye now", {linespacing=>0.6, charmap => 'Unicode', });
If GD was compiled with fontconfig support, and the fontconfig library is available on your system, then you can use a font name pattern instead of a path. Patterns are described in fontconfig and will look something like this "Times:italic". For backward compatibility, this feature is disabled by default. You must enable it by calling useFontConfig(1) prior to the stringFT() call.
$image->useFontConfig(1);
For backward compatibility with older versions of the FreeType library, the alias stringTTF() is also recognized.
This method can also be called as a class method of GD::Image;
Draws the text strings specified by top and bottom on the image, curved along the edge of a circle of radius radius, with its center at cx and cy. top is written clockwise along the top; bottom is written counterclockwise along the bottom. textRadius determines the "height" of each character; if textRadius is 1/2 of radius, characters extend halfway from the edge to the center. fillPortion varies from 0 to 1.0, with useful values from about 0.4 to 0.9, and determines how much of the 180 degrees of arc assigned to each section of text is actually occupied by text; 0.9 looks better than 1.0 which is rather crowded. font is a freetype font; see gdImageStringFT. points is passed to the freetype engine and has an effect on hinting; although the size of the text is determined by radius, textRadius, and fillPortion, you should pass a point size that "hints" appropriately -- if you know the text will be large, pass a large point size such as 24.0 to get the best results. fgcolor can be any color, and may have an alpha component, do blending, etc.
Returns a true value on success.
The alpha channel methods allow you to control the way drawings are processed according to the alpha channel. When true color is turned on, colors are encoded as four bytes, in which the last three bytes are the RGB color values, and the first byte is the alpha channel. Therefore the hexadecimal representation of a non transparent RGB color will be: C=0x00(rr)(bb)(bb)
When alpha blending is turned on, you can use the first byte of the color to control the transparency, meaning that a rectangle painted with color 0x00(rr)(bb)(bb) will be opaque, and another one painted with 0x7f(rr)(gg)(bb) will be transparent. The Alpha value must be >= 0 and <= 0x7f.
Pass a value of 1 for blending mode, and 0 for non-blending mode.
These are various utility methods that are useful in some circumstances.
GD_CMP_IMAGE The two images look different GD_CMP_NUM_COLORS The two images have different numbers of colors GD_CMP_COLOR The two images' palettes differ GD_CMP_SIZE_X The two images differ in the horizontal dimension GD_CMP_SIZE_Y The two images differ in the vertical dimension GD_CMP_TRANSPARENT The two images have different transparency GD_CMP_BACKGROUND The two images have different background colors GD_CMP_INTERLACE The two images differ in their interlace GD_CMP_TRUECOLOR The two images are not both true color
The most important of these is GD_CMP_IMAGE, which will tell you whether the two images will look different, ignoring differences in the order of colors in the color palette and other invisible changes. The constants are not imported by default, but must be imported individually or by importing the :cmp tag. Example:
use GD qw(:DEFAULT :cmp); # get $image1 from somewhere # get $image2 from somewhere if ($image1->compare($image2) & GD_CMP_IMAGE) { warn "images differ!"; }
GD does not support grouping of objects, but GD::SVG does. In that subclass, the following methods declare new groups of graphical objects:
A few primitive polygon creation and manipulation methods are provided. They aren't part of the Gd library, but I thought they might be handy to have around (they're borrowed from my qd.pl Quickdraw library). Also see GD::Polyline.
$poly = GD::Polygon->new;
$poly->addPt(0,0); $poly->addPt(0,50); $poly->addPt(25,25); $myImage->fillPoly($poly,$blue);
($x,$y) = $poly->getPt(2);
$poly->setPt(2,100,100);
($x,$y) = $poly->deletePt(1);
$poly->addPt(0,0); $poly->toPt(0,50); $poly->toPt(25,-25); $myImage->fillPoly($poly,$blue);
$points = $poly->length;
@vertices = $poly->vertices; foreach $v (@vertices) print join(",",@$v),"\n"; }
($left,$top,$right,$bottom) = $poly->bounds;
$poly->offset(10,30);
# Make the polygon really tall $poly->map($poly->bounds,0,0,50,200);
libgd:
The transformation matrix is created using 6 numbers: matrix[0] == xx matrix[1] == yx matrix[2] == xy matrix[3] == xy (probably meaning yy here) matrix[4] == x0 matrix[5] == y0 where the transformation of a given point (x,y) is given by: x_new = xx * x + xy * y + x0; y_new = yx * x + yy * y + y0;
Please see GD::Polyline for information on creating open polygons and splines.
The libgd library (used by the Perl GD library) has built-in support for about half a dozen fonts, which were converted from public-domain X Windows fonts. For more fonts, compile libgd with TrueType support and use the stringFT() call.
If you wish to add more built-in fonts, the directory bdf_scripts contains two contributed utilities that may help you convert X-Windows BDF-format fonts into the format that libgd uses internally. However these scripts were written for earlier versions of GD which included its own mini-gd library. These scripts will have to be adapted for use with libgd, and the libgd library itself will have to be recompiled and linked! Please do not contact me for help with these scripts: they are unsupported.
Each of these fonts is available both as an imported global (e.g. gdSmallFont) and as a package method (e.g. GD::Font->Small).
print "The large font contains ",gdLargeFont->nchars," characters\n";
($w,$h) = (gdLargeFont->width,gdLargeFont->height);
libgd, the C-language version of gd, can be obtained at URL http://libgd.org/ Directions for installing and using it can be found at that site. Please do not contact me for help with libgd.
The GD.pm interface is copyright 1995-2010, Lincoln D. Stein. This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text. package for details.
The latest versions of GD.pm are available at
https://github.com/lstein/Perl-GD
GD::Polyline, GD::SVG, GD::Simple, Image::Magick
2022-10-19 | perl v5.36.0 |