Seth Woolley's Man Viewer

GD(3) - GD.pm - Interface to Gd Graphics Library - man 3 GD

([section] manual, -k keyword, -K [section] search, -f whatis)
man plain no title

GD(3)                 User Contributed Perl Documentation                GD(3)



NAME
       GD.pm - Interface to Gd Graphics Library

SYNOPSIS
           use GD;

           # create a new image
           $im = new GD::Image(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;

DESCRIPTION
       GD.pm is a Perl interface to Thomas Boutell's gd graphics library (ver-
       sion(1,3,5) 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 three classes:

       "GD::Image"
            An image class, which holds the image data and accepts graphic
            primitive method calls.

       "GD::Font"
            A font class, which holds static font information and used for
            text rendering.

       "GD::Polygon"
            A simple polygon object, used for storing lists of vertices prior
            to rendering a polygon into an image.

       A Simple Example:

               #!/usr/local/bin/perl

               use GD;

               # create a new image
               $im = new GD::Image(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:

       1. To create a new, empty image, send(2,n) a new() message to GD::Image,
       passing it the width and height of the image you want to create.  An
       image object will be returned.  Other class methods allow you to ini-
       tialize an image from a preexisting JPG, PNG, GD, GD2 or XBM file.
       2. Next you will ordinarily add colors to the image's color table. col-
       ors are added using a colorAllocate() method call.  The three parame-
       ters in(1,8) each call are the red, green and blue (rgb) triples for the
       desired color.  The method returns the index of that color in(1,8) the
       image's color table.  You should store these indexes for later use.
       3. Now you can do some drawing!  The various graphics primitives are
       described below.  In this example, we do some text drawing, create an
       oval, and create and draw a polygon.
       4. Polygons are created with a new() message to GD::Polygon.  You can
       add points to the returned polygon one at a time(1,2,n) using the addPt()
       method. The polygon can then be passed to an image for rendering.
       5. When you're done drawing, you can convert the image into PNG format
       by sending it a png() message.  It will return a (potentially large)
       scalar value containing the binary data for the image.  Ordinarily you
       will print it out at this point or write(1,2) it to a file.  To ensure
       portability to platforms that differentiate between text and binary
       files, be sure to call "binmode()" on the file(1,n) you are writing the
       image to.

Object Constructors: Creating Images
       The following class methods allow you to create new GD::Image objects.

       $image = GD::Image->new([$width,$height],[$truecolor])
       $image = GD::Image->new(*FILEHANDLE)
       $image = GD::Image->new($filename)
       $image = GD::Image->new($data)
           The new() method is the main constructor for the GD::Image class.
           Called with two integer arguments, it creates a new blank image of
           the specified width and height. For example:

                   $myImage = new GD::Image(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(1,8) the red, green and blue channels respec-
           tively), allowing for precise photograph-quality color usage.  If
           not specified, the image will use an 8-bit palette for compatibil-
           ity with older versions of libgd.

           Alternatively, you may create a GD::Image object based on an exist-
           ing image by providing an open(2,3,n) filehandle, a filename, or the image
           data itself.  The image formats automatically recognized and
           accepted are: PNG, JPEG, XPM and GD2.  Other formats, including
           WBMP, and GD version(1,3,5) 1, cannot be recognized automatically at this
           time.

           If something goes wrong (e.g. insufficient memory), this call will
           return undef.

       $image = GD::Image->trueColor([0,1])
           For backwards compatibility with scripts previous versions of GD,
           new images created from scratch (width, height) are palette based
           by default.  To change this default to create true color images
           use:

                   GD::Image->trueColor(1);

           somewhere before creating new images.  To switch(1,n) back to palette
           based by default, use:

                   GD::Image->trueColor(0);

       $image = GD::Image->newPalette([$width,$height])
       $image = GD::Image->newTrueColor([$width,$height])
           The newPalette() and newTrueColor() methods can be used to explic-
           itly create an palette based or true color image regardless of the
           current setting of trueColor().

       $image = GD::Image->newFromPng($file(1,n), [$truecolor])
       $image = GD::Image->newFromPngData($data, [$truecolor])
           The newFromPng() method will create an image from a PNG file(1,n) read(2,n,1 builtins)
           in(1,8) through the provided filehandle or file(1,n) path.  The filehandle
           must previously have been opened on a valid PNG file(1,n) or pipe.  If
           successful, this call will return an initialized image which you
           can then manipulate as you please.  If it fails, which usually hap-
           pens if(3,n) the thing at the other end of the filehandle is not a valid
           PNG file(1,n), the call returns undef.  Notice that the call doesn't
           automatically close(2,7,n) the filehandle for you.  But it does call "bin-
           mode(FILEHANDLE)" for you, on platforms where this matters.  The
           optional $truecolor (0/1) value can be used to override the global
           setting of trueColor() to specify if(3,n) the return image should be
           palette-based or truecolor.

           You may use any of the following as the argument:

             1) a simple filehandle, such as STDIN
             2) a filehandle glob(1,3,7,n), such as *PNG
             3) a reference to a glob(1,3,7,n), such as \*PNG
             4) an IO::Handle object
             5) the pathname of a file(1,n)

           In the latter case, newFromPng() will attempt to open(2,3,n) the file(1,n) for
           you and read(2,n,1 builtins) the PNG information from it.

             Example1:

             open(2,3,n) (PNG,"barnswallow.png") || die;
             $myImage = newFromPng GD::Image(\*PNG) || die;
             close(2,7,n) PNG;

             Example2:
             $myImage = newFromPng GD::Image('barnswallow.png');

           To get information about the size and color usage of the informa-
           tion, you can call the image query methods described below.

           The newFromPngData() method will create a new GD::Image initialized
           with the PNG format data contained in(1,8) $data.

       $image = GD::Image->newFromJpeg($file(1,n), [$truecolor])
       $image = GD::Image->newFromJpegData($data, [$truecolor])
           These methods will create an image from a JPEG file.  They work
           just like newFromPng() and newFromPngData(), and will accept(2,8) the
           same filehandle and pathname arguments.  The optional $truecolor
           (0/1) value can be used to override the global setting of true-
           Color() to specify if(3,n) the return image should be palette-based or
           truecolor.

           Bear in(1,8) mind that JPEG is a 24-bit format, while GD is 8-bit.  This
           means that photographic images will become posterized.

       $image = GD::Image->newFromXbm($file(1,n))
           This works in(1,8) exactly the same way as "newFromPng", but reads the
           contents of an X Bitmap (black & white) file:

                   open(2,3,n) (XBM,"coredump.xbm") || die;
                   $myImage = newFromXbm GD::Image(\*XBM) || die;
                   close(2,7,n) XBM;

           There is no newFromXbmData() function, because there is no corre-
           sponding function in(1,8) the gd library.

       $image = GD::Image->newFromWMP($file(1,n))
           This creates a new GD::Image object starting from a WBMP-format
           file(1,n) or filehandle.  There is currently no newFromWMPData() method.

       $image = GD::Image->newFromGd($file(1,n))
       $image = GD::Image->newFromGdData($data)
           These methods initialize a GD::Image from a Gd file(1,n), filehandle, or
           data.  Gd is Tom Boutell's disk-based storage format, intended for
           the rare case when you need to read(2,n,1 builtins) and write(1,2) 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 = newFromGd GD::Image("godzilla.gd") || die;
                   close(2,7,n) GDF;

       $image = GD::Image->newFromGd2($file(1,n))
       $image = GD::Image->newFromGd2Data($data)
           This works in(1,8) exactly the same way as "newFromGd()" and
           newFromGdData, but use the new compressed GD2 image format.

       $image = GD::Image->newFromGd2Part($file(1,n),srcX,srcY,width,height)
           This class method allows you to read(2,n,1 builtins) in(1,8) just a portion of a GD2
           image file.  In additionto a filehandle, it accepts the top-left
           corner and dimensions (width,height) of the region of the image to
           read.  For example:

                   open(2,3,n) (GDF,"godzilla.gd2") || die;
                   $myImage = GD::Image->newFromGd2Part(\*GDF,10,20,100,100) || die;
                   close(2,7,n) GDF;

           This reads a 100x100 square portion of the image starting from
           position (10,20).

       $image = GD::Image->newFromXpm($filename)
           This creates a new GD::Image object starting from a filename.  This
           is unlike the other newFrom() functions because it does not take a
           filehandle.  This difference comes from an inconsistency in(1,8) the
           underlying gd library.

                   $myImage = newFromXpm GD::Image('earth.xpm') || die;

           This function is only available if(3,n) libgd was compiled with XPM sup-
           port.

           NOTE: The libgd library is unable to read(2,n,1 builtins) certain XPM files,
           returning an all-black image instead.

GD::Image Methods
       Once a GD::Image object is created, you can draw with it, copy it, and
       merge(1,8) two images.  When you are finished manipulating the object, you
       can convert it into a standard image file(1,n) format to output or save to a
       file.

       Image Data Output Methods

       The following methods convert the internal drawing format into standard
       output file(1,n) formats.

       $pngdata = $image->png([$compression_level])
           This returns the image data in(1,8) PNG format.  You can then print it,
           pipe(2,8) it to a display program, or write(1,2) it to a file.  Example:

                   $png_data = $myImage->png;
                   open(2,3,n) (DISPLAY,"| display -") || die;
                   binmode DISPLAY;
                   print DISPLAY $png_data;
                   close(2,7,n) 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).

       $jpegdata = $image->jpeg([$quality])
           This returns the image data in(1,8) JPEG format.  You can then print it,
           pipe(2,8) it to a display program, or write(1,2) it to a file.  You may pass
           an optional quality score to jpeg() in(1,8) order to control the JPEG
           quality.  This should be an integer between 0 and 100.  Higher
           quality scores give larger files and better image quality.  If you
           don't specify the quality, jpeg() will choose a good default.

       $gddata = $image->gd
           This returns the image data in(1,8) GD format.  You can then print it,
           pipe(2,8) it to a display program, or write(1,2) it to a file.  Example:

                   binmode MYOUTFILE;
                   print MYOUTFILE $myImage->gd;

       $gd2data = $image->gd2
           Same as gd(), except that it returns the data in(1,8) compressed GD2
           format.

       $wbmpdata = $image->wbmp([$foreground])
           This returns the image data in(1,8) WBMP format, which is a black-and-
           white image format.  Provide the index of the color to become the
           foreground color.  All other pixels will be considered background.

       Color Control

       These methods allow you to control and manipulate the GD::Image color
       table.

       $index = $image->colorAllocate(red,green,blue)
           This allocates a color with the specified red, green and blue com-
           ponents and returns its index in(1,8) the color table, if(3,n) specified.
           The first color allocated in(1,8) this way becomes the image's back-
           ground color.  (255,255,255) is white (all pixels on).  (0,0,0) is
           black (all pixels off).  (255,0,0) is fully saturated red.
           (127,127,127) is 50% gray.  You can find plenty of examples in(1,8)
           /usr/X11/lib/X11/rgb.txt.

           If no colors are allocated, then this function returns -1.

           Example:

                   $white = $myImage->colorAllocate(0,0,0); #background color
                   $black = $myImage->colorAllocate(255,255,255);
                   $peachpuff = $myImage->colorAllocate(255,218,185);

       $index = $image->colorAllocateAlpha(reg,green,blue,alpha)
           This allocates a color with the specified red, green, and blue com-
           ponents, plus the specified alpha channel.  The alpha value may
           range from 0 (opaque) to 127 (transparent).  The "alphaBlending"
           function changes the way this alpha channel affects the resulting
           image.

       $index = $image->colorAllocateAlpha(reg,green,blue,alpha)
           This allocates a color with the specified red, green, and blue com-
           ponents, plus the specified alpha channel.  The alpha value may
           range from 0 (opaque) to 127 (transparent).  The "alphaBlending"
           function changes the way this alpha channel affects the resulting
           image.

       $image->colorDeallocate(colorIndex)
           This marks the color at the specified index as being ripe for real-
           location.  The next time(1,2,n) colorAllocate is used, this entry will be
           replaced.  You can call this method several times to deallocate
           multiple colors.  There's no function result from this call.

           Example:

                   $myImage->colorDeallocate($peachpuff);
                   $peachy = $myImage->colorAllocate(255,210,185);

       $index = $image->colorClosest(red,green,blue)
           This returns the index of the color closest in(1,8) the color table to
           the red green and blue components specified.  If no colors have yet
           been allocated, then this call returns -1.

           Example:

                   $apricot = $myImage->colorClosest(255,200,180);

       $index = $image->colorClosestHWB(red,green,blue)
           This also attempts to return the color closest in(1,8) the color table
           to the red green and blue components specified. If uses a
           Hue/White/Black color representation to make the selected colour
           more likely to match human perceptions of similar colors.

           If no colors have yet been allocated, then this call returns -1.

           Example:

                   $mostred = $myImage->colorClosestHWB(255,0,0);

       $index = $image->colorExact(red,green,blue)
           This returns the index of a color that exactly matches the speci-
           fied red green and blue components.  If such a color is not in(1,8) the
           color table, this call returns -1.

                   $rosey = $myImage->colorExact(255,100,80);
                   warn "Everything's coming up roses.\n" if(3,n) $rosey >= 0;

       $index = $image->colorResolve(red,green,blue)
           This returns the index of a color that exactly matches the speci-
           fied red green and blue components.  If such a color is not in(1,8) the
           color table and there is room, then this method allocates the color
           in(1,8) the color table and returns its index.

                   $rosey = $myImage->colorResolve(255,100,80);
                   warn "Everything's coming up roses.\n" if(3,n) $rosey >= 0;

       $colorsTotal = $image->colorsTotal) object method
           This returns the total number of colors allocated in(1,8) the object.

                   $maxColors = $myImage->colorsTotal;

       $index = $image->getPixel(x,y) object method
           This returns the color table index underneath the specified point.
           It can be combined with rgb() to obtain the rgb color underneath
           the pixel.

           Example:

                   $index = $myImage->getPixel(20,100);
                   ($r,$g,$b) = $myImage->rgb($index);

       ($red,$green,$blue) = $image->rgb($index)
           This returns a list containing the red, green and blue components
           of the specified color index.

           Example:

                   @RGB = $myImage->rgb($peachy);

       $image->transparent($colorIndex)
           This marks the color at the specified index as being transparent.
           Portions of the image drawn in(1,8) this color will be invisible.  This
           is useful for creating paintbrushes of odd shapes, as well as for
           making PNG backgrounds transparent for displaying on the Web.  Only
           one color can be transparent at any time. To disable transparency,
           specify -1 for the index.

           If you call this method without any parameters, it will return the
           current index of the transparent color, or -1 if(3,n) none.

           Example:

                   open(2,3,n)(PNG,"test.png");
                   $im = newFromPng GD::Image(PNG);
                   $white = $im->colorClosest(255,255,255); # find white
                   $im->transparent($white);
                   binmode STDOUT;
                   print $im->png;

       Special Colors

       GD implements a number of special colors that can be used to achieve
       special effects.  They are constants defined in(1,8) the GD:: namespace, but
       automatically exported into your namespace when the GD module is
       loaded.

       $image->setBrush($image)
           You can draw lines and shapes using a brush pattern.  Brushes are
           just images that you can create and manipulate in(1,8) the usual way.
           When you draw with them, their contents are used for the color and
           shape of the lines.

           To make a brushed line, you must create or load(7,n) the brush first,
           then assign it to the image using setBrush().  You can then draw in(1,8)
           that with that brush using the gdBrushed special color.  It's often
           useful to set(7,n,1 builtins) 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 = new GD::Image(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);

       $image->setThickness($thickness)
           Lines drawn with line(), rectangle(), arc(), and so forth are 1
           pixel thick by default.  Call setThickness() to change the line
           drawing width.

       $image->setStyle(@colors)
           Styled lines consist of an arbitrary series of repeated colors and
           are useful for generating dotted and dashed lines.  To create a
           styled line, use setStyle() to specify a repeating series of col-
           ors.  It accepts an array consisting of one or more color indexes.
           Then draw using the gdStyled special color.  Another special color,
           gdTransparent can be used to introduce holes in(1,8) the line, as the
           example shows.

           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 spec-
           ify "gdStyledBrushed".  In this case, a pixel from the current
           brush pattern is rendered wherever the color specified in(1,8) set-
           Style() is neither gdTransparent nor 0.

       gdTiled
           Draw filled shapes and flood fills using a pattern.  The pattern is
           just another image.  The image will be tiled multiple times in(1,8)
           order to fill the required space, creating wallpaper effects.  You
           must call "setTile" in(1,8) order to define the particular tile pattern
           you'll use for drawing when you specify the gdTiled color.
           details.

       gdStyled
           The gdStyled color is used for creating dashed and dotted lines.  A
           styled line can contain any series of colors and is created using
           the setStyled() command.

       gdAntiAliased
           The "gdAntiAliased" color is used for drawing lines with antialias-
           ing turned on.  Antialiasing will blend the jagged edges of lines
           with the background, creating a smoother look.  The actual color
           drawn is set(7,n,1 builtins) with setAntiAliased().

       $image->setAntiAliased($color)
           "Antialiasing" is a process by which jagged edges associated with
           line drawing can be reduced by blending the foreground color with
           an appropriate percentage of the background, depending on how much
           of the pixel in(1,8) question is actually within the boundaries of the
           line being drawn. All line-drawing methods, such as line() and
           polygon, will draw antialiased lines if(3,n) the special "color" gdAn-
           tiAliased is used when calling them.

           setAntiAliased() is used to specify the actual foreground color to
           be used when drawing antialiased lines. You may set(7,n,1 builtins) any color to be
           the foreground, however as of libgd version(1,3,5) 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 com-
           plex palette-based backgrounds may not give satisfactory results,
           due to the limited number of colors available in(1,8) the palette.
           Antialiased line-drawing on simple backgrounds should work well
           with palette-based images; otherwise create or fetch a truecolor
           image instead.

       $image->setAntiAliasedDontBlend($color,[$flag])
           Normally, when drawing lines with the special gdAntiAliased
           "color," blending with the background to reduce jagged edges is the
           desired behavior. However, when it is desired that lines not be
           blended with one particular color when it is encountered in(1,8) the
           background, the setAntiAliasedDontBlend() method can be used to
           indicate the special color that the foreground should stand out
           more clearly against.

           Once turned on, you can turn this feature off by calling setAn-
           tiAliasedDontBlend() with a second argument of 0:

            $image->setAntiAliasedDontBlend($color,0);

       Drawing Commands

       These methods allow you to draw lines, rectangles, and elipses, as well
       as to perform various special operations like flood-fill.

       $image->setPixel($x,$y,$color)
           This sets the pixel at (x,y) to the specified color index.  No
           value is returned from this method.  The coordinate system starts
           at the upper left at (0,0) and gets(3,n) larger as you go down and to
           the right.  You can use a real color, or one of the special colors
           gdBrushed, gdStyled and gdStyledBrushed can be specified.

           Example:

                   # This assumes $peach already allocated
                   $myImage->setPixel(50,50,$peach);

       $image->line($x1,$y1,$x2,$y2,$color)
           This draws a line from (x1,y1) to (x2,y2) of the specified color.
           You can use a real color, or one of the special colors gdBrushed,
           gdStyled and gdStyledBrushed.

           Example:

                   # Draw a diagonal line using the currently defind
                   # paintbrush pattern.
                   $myImage->line(0,0,150,150,gdBrushed);

       $image->dashedLine($x1,$y1,$x2,$y2,$color)
           This draws a dashed line from (x1,y1) to (x2,y2) in(1,8) 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);

       GD::Image::rectangle($x1,$y1,$x2,$y2,$color)
           This draws a rectangle with the specified color.  (x1,y1) and
           (x2,y2) are the upper left and lower right corners respectively.
           Both real color indexes and the special colors gdBrushed, gdStyled
           and gdStyledBrushed are accepted.

           Example:

                   $myImage->rectangle(10,10,100,100,$rose(3,4));

       $image->filledRectangle($x1,$y1,$x2,$y2,$color)
           This draws a rectangle filed with the specified color.  You can use
           a real color, or the special fill color gdTiled to fill the polygon
           with a pattern.

           Example:

                   # read(2,n,1 builtins) in(1,8) a fill pattern and set(7,n,1 builtins) it
                   $tile = newFromPng GD::Image('happyface.png');
                   $myImage->setTile($tile);

                   # draw the rectangle, filling it with the pattern
                   $myImage->filledRectangle(10,10,150,200,gdTiled);

       $image->polygon($polygon,$color)
           This draws a polygon with the specified color.  The polygon must be
           created first (see below).  The polygon must have at least three
           vertices.  If the last vertex doesn't close(2,7,n) the polygon, the method
           will close(2,7,n) it for you.  Both real color indexes and the special
           colors gdBrushed, gdStyled and gdStyledBrushed can be specified.

           Example:

                   $poly = new GD::Polygon;
                   $poly->addPt(50,0);
                   $poly->addPt(99,99);
                   $poly->addPt(0,99);
                   $myImage->polygon($poly,$blue);

       $image->filledPolygon($poly,$color)
           This draws a polygon filled with the specified color.  You can use
           a real color, or the special fill color gdTiled to fill the polygon
           with a pattern.

           Example:

                   # make a polygon
                   $poly = new GD::Polygon;
                   $poly->addPt(50,0);
                   $poly->addPt(99,99);
                   $poly->addPt(0,99);

                   # draw the polygon, filling it with a color
                   $myImage->filledPolygon($poly,$peachpuff);

       $image->ellipse($cx,$cy,$width,$height,$color)
       $image->filledEllipse($cx,$cy,$width,$height,$color)
           These methods() draw ellipses. ($cx,$cy) is the center of the arc,
           and ($width,$height) specify the ellipse width and height, respec-
           tively.  filledEllipse() is like Ellipse() except that the former
           produces filled versions of the ellipse.

       $image->arc($cx,$cy,$width,$height,$start,$end,$color)
           This draws arcs and ellipses.  (cx,cy) are the center of the arc,
           and (width,height) specify the width and height, respectively.  The
           portion of the ellipse covered by the arc are controlled by start
           and end, both of which are given in(1,8) degrees from 0 to 360.  Zero is
           at the top of the ellipse, and angles increase clockwise.  To spec-
           ify a complete ellipse, use 0 and 360 as the starting and ending
           angles.  To draw a circle, use the same value for width and height.

           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);

       $image->filledArc($cx,$cy,$width,$height,$start,$end,$color
       [,$arc_style])
           This method is like arc() except that it colors in(1,8) the pie wedge
           with the selected color.  $arc_style is optional.  If present it is
           a bitwise OR of the following constants:

             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 mutally exclusive.  gdChord just connects the
           starting and ending angles with a straight line, while gdArc pro-
           duces a rounded edge. gdPie is a synonym for gdArc. gdNoFill indi-
           cates 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);

       $image->fill($x,$y,$color)
           This method flood-fills regions with the specified color.  The
           color will spread through the image, starting at point (x,y), until
           it is stopped by a pixel of a different color from the starting
           pixel (this is similar to the "paintbucket" in(1,8) many popular drawing
           toys).  You can specify a normal color, or the special color
           gdTiled, to flood-fill with patterns.

           Example:

                   # Draw a rectangle, and then make its interior blue
                   $myImage->rectangle(10,10,100,100,$black);
                   $myImage->fill(50,50,$blue);

       $image->fillToBorder($x,$y,$bordercolor,$color)
           Like "fill", this method flood-fills regions with the specified
           color, starting at position (x,y).  However, instead of stopping
           when it hits a pixel of a different color than the starting pixel,
           flooding will only stop when it hits the color specified by border-
           color.  You must specify a normal indexed color for the border-
           color.  However, you are free to use the gdTiled color for the
           fill.

           Example:

                   # This has the same effect as the previous example
                   $myImage->rectangle(10,10,100,100,$black);
                   $myImage->fillToBorder(50,50,$black,$blue);

       Image Copying Commands

       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.

       $image->copy($sourceImage,$dstX,$dstY,
                               $srcX,$srcY,$width,$height)

           This is the simplest of the several copy operations, copying the
           specified region from the source image to the destination image
           (the one performing the method call).  (srcX,srcY) specify the
           upper left corner of a rectangle in(1,8) the source image, and
           (width,height) give the width and height of the region to copy.
           (dstX,dstY) control where in(1,8) the destination image to stamp the
           copy.  You can use the same image for both the source and the des-
           tination, but the source and destination regions must not overlap
           or strange things will happen.

           Example:

                   $myImage = new GD::Image(100,100);
                   ... various drawing stuff ...
                   $srcImage = new GD::Image(50,50);
                   ... more drawing stuff ...
                   # copy a 25x25 pixel region from $srcImage to
                   # the rectangle starting at (10,10) in(1,8) $myImage
                   $myImage->copy($srcImage,10,10,0,0,25,25);

       $image->clone()
           Make a copy of the image and return it as a new object.  The new
           image will look(1,8,3 Search::Dict) identical.  However, it may differ in(1,8) the size of
           the color palette and other nonessential details.

           Example:

                   $myImage = new GD::Image(100,100);
                   ... various drawing stuff ...
                   $copy = $myImage->clone;

       $image->copyMerge($sourceImage,$dstX,$dstY,
                               $srcX,$srcY,$width,$height,$percent)

           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(1,8) a solid rectangle.

           Example:

                   $myImage = new GD::Image(100,100);
                   ... various drawing stuff ...
                   $redImage = new GD::Image(50,50);
                   ... more drawing stuff ...
                   # copy a 25x25 pixel region from $srcImage to
                   # the rectangle starting at (10,10) in(1,8) $myImage, merging 50%
                   $myImage->copyMerge($srcImage,10,10,0,0,25,25,50);

       $image->copyMergeGray($sourceImage,$dstX,$dstY,
                               $srcX,$srcY,$width,$height,$percent)

           This is identical to copyMerge() except that it preserves the hue
           of the source by converting all the pixels of the destination rec-
           tangle to grayscale before merging.

       $image->copyResized($sourceImage,$dstX,$dstY,
                               $srcX,$srcY,$destW,$destH,$srcW,$srcH)

           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 accomodate the size requirements.

           Example:

                   $myImage = new GD::Image(100,100);
                   ... various drawing stuff ...
                   $srcImage = new GD::Image(50,50);
                   ... more drawing stuff ...
                   # copy a 25x25 pixel region from $srcImage to
                   # a larger rectangle starting at (10,10) in(1,8) $myImage
                   $myImage->copyResized($srcImage,10,10,0,0,50,50,25,25);

       $image->copyResampled($sourceImage,$dstX,$dstY,
                               $srcX,$srcY,$destW,$destH,$srcW,$srcH)

           This method is similar to copyResized() but provides "smooth" copy-
           ing from a large image to a smaller one, using a weighted average
           of the pixels of the source area rather than selecting one repre-
           sentative pixel. This method is identical to copyResized() when the
           destination image is a palette image.

       $image->trueColorToPalette([$dither], [$colors])
           This method converts a truecolor image to a palette image. The code
           for this function was originally drawn from the Independent JPEG
           Group library code, which is excellent. The code has been modified
           to preserve as much alpha channel information as possible in(1,8) the
           resulting palette, in(1,8) addition to preserving colors as well as pos-
           sible. This does not work as well as might be hoped. It is usually
           best to simply produce a truecolor output image instead, which
           guarantees the highest output quality.  Both the dithering (0/1,
           default=0) and maximum number of colors used (<=256, default =
           gdMaxColors) can be specified.

       Image Transformation Commands

       Gd also provides some common image transformations:

       $image = $sourceImage->copyRotate90()
       $image = $sourceImage->copyRotate180()
       $image = $sourceImage->copyRotate270()
       $image = $sourceImage->copyFlipHorizontal()
       $image = $sourceImage->copyFlipVertical()
       $image = $sourceImage->copyTranspose()
       $image = $sourceImage->copyReverseTranspose()
           These methods can be used to rotate, flip, or transpose an image.
           The result of the method is a copy of the image.

       $image->rotate180()
       $image->flipHorizontal()
       $image->flipVertical()
           These methods are similar to the copy* versions, but instead modify
           the image in(1,8) place.

       Character and String Drawing

       Gd allows you to draw characters and strings, either in(1,8) normal horizon-
       tal orientation or rotated 90 degrees.  These routines use a GD::Font
       object, described in(1,8) more detail below.  There are four built-in fonts,
       available in(1,8) global variables gdGiantFont, gdLargeFont, gdMediumBold-
       Font, gdSmallFont and gdTinyFont.  Currently there is no way of dynami-
       cally creating your own fonts.

       $image->string(3,n)($font,$x,$y,$string(3,n),$color)
           This method draws a string(3,n) startin at position (x,y) in(1,8) the speci-
           fied font and color.  Your choices of fonts are gdSmallFont,
           gdMediumBoldFont, gdTinyFont, gdLargeFont and gdGiantFont.

           Example:

                   $myImage->string(3,n)(gdSmallFont,2,10,"Peachy Keen",$peach);

       $image->stringUp($font,$x,$y,$string(3,n),$color)
           Just like the previous call, but draws the text rotated counter-
           clockwise 90 degrees.

       $image->char($font,$x,$y,$char,$color)
       $image->charUp($font,$x,$y,$char,$color)
           These methods draw single characters at position (x,y) in(1,8) the spec-
           ified font and color.  They're carry-overs from the C interface,
           where there is a distinction between characters and strings.  Perl
           is insensible to such subtle distinctions.

       @bounds = $image->stringFT($fgcolor,$font-
       name,$ptsize,$angle,$x,$y,$string(3,n))
       @bounds = GD::Image->stringFT($fgcolor,$font-
       name,$ptsize,$angle,$x,$y,$string(3,n))
       @bounds = $image->stringFT($fgcolor,$font-
       name,$ptsize,$angle,$x,$y,$string(3,n),\%options)
           This method uses TrueType to draw a scaled, antialiased string(3,n)
           using the TrueType vector font of your choice.  It requires that
           libgd to have been compiled with TrueType support, and for the
           appropriate TrueType font to be installed on your system.

           The arguments are as follows:

             fgcolor    Color index to draw the string(3,n) in(1,8)
             fontname   An absolute path to the TrueType (.ttf) font file(1,n)
             ptsize     The desired point size (may be fractional)
             angle      The rotation angle, in(1,8) radians
             x,y        X and Y coordinates to start drawing the string(3,n)
             string(3,n)     The string(3,n) 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(8,n) (such as the font not being available, or FT
           support not being available), the method returns an empty list and
           sets $@ to the error(8,n) message.

           You may also call this method from the GD::Image class name, in(1,8)
           which case it doesn't do any actual drawing, but returns the bound-
           ing box using an inexpensive operation.  You can use this to per-
           form layout operations prior to drawing.

           Using a negative color index will disable anti-aliasing, as
           described in(1,8) 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().  Two hashkeys are recognized: linespacing, if(3,n) present,
           controls the spacing between lines of text.  charmap, if(3,n) present,
           sets the character map to use.

           The value of linespacing is supposed to be a multiple of the char-
           acter height, so setting linespacing to 2.0 will result in(1,8) double-
           spaced lines of text.  However the current version(1,3,5) of libgd
           (2.0.12) does not do this.  Instead the linespacing seems to be
           double what is provided in(1,8) 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(1,2) 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(1,3x,3x clrtobot) to me,
           and you should experiment a bit if(3,n) you want to use this feature.

           Example:

            $gd->stringFT($black,'/dosc/windows/Fonts/pala.ttf',40,0,20,90,
                         "hi there\r\nbye now",
                         {linespacing=>0.6,
                          charmap  => 'Unicode',
                         });

           For backward compatibility with older versions of the FreeType
           library, the alias stringTTF() is also recognized.  Also be aware
           that relative font paths are not recognized due to problems in(1,8) the
           libgd library.

       Alpha channels

       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(1,8) 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.

       $image->alphaBlending($blending)
           The alphaBlending() method allows for two different modes of draw-
           ing on truecolor images. In blending mode, which is on by default
           (libgd 2.0.2 and above), the alpha channel component of the color
           supplied to all drawing functions, such as "setPixel", determines
           how much of the underlying color should be allowed to shine
           through. As a result, GD automatically blends the existing color at
           that point with the drawing color, and stores the result in(1,8) the
           image. The resulting pixel is opaque. In non-blending mode, the
           drawing color is copied literally with its alpha channel informa-
           tion, replacing the destination pixel. Blending mode is not avail-
           able when drawing on palette images.

       $image->saveAlpha($saveAlpha)
           By default, GD (libgd 2.0.2 and above) does not attempt to save
           full alpha channel information (as opposed to single-color trans-
           parency) when saving PNG images. (PNG is currently the only output
           format supported by gd which can accommodate alpa channel informa-
           tion.) This saves space in(1,8) the output file. If you wish to create
           an image with alpha channel information for use with tools that
           support it, call saveAlpha(1) to turn on saving of such informa-
           tion, and call alphaBlending(0) to turn off alpha blending within
           the library so that alpha channel information is actually stored in(1,8)
           the image rather than being composited immediately at the time(1,2,n) that
           drawing functions are invoked.

       Miscellaneous Image Methods

       These are various utility methods that are useful in(1,8) some circum-
       stances.

       $image->interlaced([$flag])
           This method sets or queries the image's interlaced setting.  Inter-
           lace produces a cool venetian blinds effect on certain viewers.
           Provide a true parameter to set(7,n,1 builtins) the interlace attribute.  Provide
           undef to disable it.  Call the method without parameters to find
           out the current setting.

       ($width,$height) = $image->getBounds()
           This method will return a two-member list containing the width and
           height of the image.  You query but not not change the size of the
           image once it's created.

       $is_truecolor = $image->isTrueColor()
           This method will return a boolean representing whether the image is
           true color or not.

       $flag = $image1->compare($image2)
           Compare two images and return a bitmap describing the differenes
           found, if(3,n) any.  The return value must be logically ANDed with one
           or more constants in(1,8) order to determine the differences.  The fol-
           lowing constants are available:

             GD_CMP_IMAGE             The two images look(1,8,3 Search::Dict) 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(1,8) the horizontal dimension
             GD_CMP_SIZE_Y            The two images differ in(1,8) 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(1,8) 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(1,8,3 Search::Dict) different, ignoring differences in(1,8)
           the order of colors in(1,8) 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(3,n) ($image1->compare($image2) & GD_CMP_IMAGE) {
                warn "images differ!";
             }

       $image->clip($x1,$y1,$x2,$y2)
       ($x1,$y1,$x2,$y2) = $image->clip
           Set or get the clipping rectangle.  When the clipping rectangle is
           set(7,n,1 builtins), all drawing will be clipped to occur within this rectangle.
           The clipping rectangle is initially set(7,n,1 builtins) to be equal to the bound-
           aries of the whole image. Change it by calling clip() with the
           coordinates of the new clipping rectangle.  Calling clip() without
           any arguments will return the current clipping rectangle.

       $flag = $image->boundsSafe($x,$y)
           The boundsSafe() method will return true if(3,n) the point indicated by
           ($x,$y) is within the clipping rectangle, or false if(3,n) it is not.
           If the clipping rectangle has not been set(7,n,1 builtins), then it will return
           true if(3,n) the point lies within the image boundaries.

Polygons
       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
          Create an empty polygon with no vertices.

                  $poly = new GD::Polygon;

       $poly->addPt($x,$y)
          Add point (x,y) to the polygon.

                  $poly->addPt(0,0);
                  $poly->addPt(0,50);
                  $poly->addPt(25,25);
                  $myImage->fillPoly($poly,$blue);

       ($x,$y) = $poly->getPt($index)
          Retrieve the point at the specified vertex.

                  ($x,$y) = $poly->getPt(2);

       $poly->setPt($index,$x,$y)
          Change the value of an already existing vertex.  It is an error(8,n) to
          set(7,n,1 builtins) a vertex that isn't already defined.

                  $poly->setPt(2,100,100);

       ($x,$y) = $poly->deletePt($index)
          Delete the specified vertex, returning its value.

                  ($x,$y) = $poly->deletePt(1);

       $poly->toPt($dx,$dy)
          Draw from current vertex to a new vertex, using relative (dx,dy)
          coordinates.  If this is the first point, act like addPt().

                  $poly->addPt(0,0);
                  $poly->toPt(0,50);
                  $poly->toPt(25,-25);
                  $myImage->fillPoly($poly,$blue);

       $vertex_count = $poly->length
          Return the number of vertices in(1,8) the polygon.

                  $points = $poly->length;

       @vertices = $poly->vertices
          Return a list of all the verticies in(1,8) the polygon object.  Each mem-
          ber of the list is a reference to an (x,y) array.

                  @vertices = $poly->vertices;
                  foreach $v (@vertices)
                     print join(1,n)(",",@$v),"\n";
                  }

       @rect = $poly->bounds
          Return the smallest rectangle that completely encloses the polygon.
          The return value is an array containing the (left,top,right,bottom)
          of the rectangle.

                  ($left,$top,$right,$bottom) = $poly->bounds;

       $poly->offset($dx,$dy)
          Offset all the vertices of the polygon by the specified horizontal
          (dh) and vertical (dy) amounts.  Positive numbers move(3x,7,3x curs_move) the polygon
          down and to the right.

                  $poly->offset(10,30);

       $poly->map($srcL,$srcT,$srcR,$srcB,$destL,$dstT,$dstR,$dstB)
          Map the polygon from a source rectangle to an equivalent position in(1,8)
          a destination rectangle, moving it and resizing it as necessary.
          See polys.pl for an example of how this works.  Both the source and
          destination rectangles are given in(1,8) (left,top,right,bottom) coordi-
          nates.  For convenience, you can use the polygon's own bounding box
          as the source rectangle.

                  # Make the polygon really tall
                  $poly->map($poly->bounds,0,0,50,200);

       $poly->scale($sx,$sy)
          Scale each vertex of the polygon by the X and Y factors indicated by
          sx and sy.  For example scale(2,2) will make the polygon twice as
          large.  For best results, move(3x,7,3x curs_move) the center of the polygon to position
          (0,0) before you scale, then move(3x,7,3x curs_move) it back to its previous position.

       $poly->transform($sx,$rx,$sy,$ry,$tx,$ty)
          Run each vertex of the polygon through a transformation matrix,
          where sx and sy are the X and Y scaling factors, rx and ry are the X
          and Y rotation factors, and tx and ty are X and Y offsets.  See the
          Adobe PostScript Reference, page 154 for a full explanation, or
          experiment.

       GD::Polyline

       Please see GD::Polyline for information on creating open(2,3,n) polygons and
       splines.

Font Utilities
       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 con-
       tains 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. gdS-
       mallFont) and as a package method (e.g. GD::Font->Small).

       gdSmallFont
       GD::Font->Small
            This is the basic small font, "borrowed" from a well known public
            domain 6x12 font.

       gdLargeFont
       GD::Font->Large
            This is the basic large font, "borrowed" from a well known public
            domain 8x16 font.

       gdMediumBoldFont
       GD::Font->MediumBold
            This is a bold font intermediate in(1,8) size between the small and
            large fonts, borrowed from a public domain 7x13 font;

       gdTinyFont
       GD::Font->Tiny
            This is a tiny, almost unreadable font, 5x8 pixels wide.

       gdGiantFont
       GD::Font->Giant
            This is a 9x15 bold font converted by Jan Pazdziora from a sans
            serif X11 font.

       $font->nchars
            This returns the number of characters in(1,8) the font.

                    print "The large font contains ",gdLargeFont->nchars," characters\n";

       $font->offset
            This returns the ASCII value of the first character in(1,8) the font

       $width = $font->width
       $height = $font->height
       "height"
            These return the width and height of the font.

              ($w,$h) = (gdLargeFont->width,gdLargeFont->height);

Obtaining the C-language version(1,3,5) of gd
       libgd, the C-language version(1,3,5) of gd, can be obtained at URL
       http://www.boutell.com/gd/.  Directions for installing and using it can
       be found at that site.  Please do not contact me for help with libgd.

AUTHOR
       The GD.pm interface is copyright 1995-2000, Lincoln D. Stein.  It is
       distributed under the same terms as Perl itself.  See the "Artistic
       License" in(1,8) the Perl source code distribution for licensing terms.

       The latest versions of GD.pm are available at

         http://stein.cshl.org/WWW/software/GD

SEE ALSO
       GD::Polyline, Image::Magick



perl v5.8.4                       2002-07-30                             GD(3)

References for this manual (incoming links)