Scroll to navigation

SVG(3pm) User Contributed Perl Documentation SVG(3pm)

NAME

GD::SVG - Seamlessly enable SVG output from scripts written using GD

SYNOPSIS

    # use GD;
    use GD::SVG;
    # my $img = GD::Image->new();
    my $img = GD::SVG::Image->new();
    # $img->png();
    $img->svg();

DESCRIPTION

GD::SVG painlessly enables scripts that utilize GD to export scalable vector graphics (SVG). It accomplishes this task by wrapping SVG.pm with GD-styled method calls. To enable this functionality, one need only change the "use GD" call to "use GD::SVG" (and initial "new" method calls).

EXPORTS

GD::SVG exports the same methods as GD itself, overriding those methods.

USAGE

In order to generate SVG output from your script using GD::SVG, you will need to first

  # use GD;
  use GD::SVG;

After that, each call to the package classes that GD implements should be changed to GD::SVG. Thus:

  GD::Image    becomes  GD::SVG::Image
  GD::Font     becomes  GD::SVG::Font

DYNAMICALLY SELECTING SVG OUTPUT

If you would like your script to be able to dynamically select either PNG or JPEG output (via GD) or SVG output (via GD::SVG), you should place your "use" statement within an eval. In the example below, each of the available classes is created at the top of the script for convenience, as well as the image output type.

  my $package = shift;
  eval "use $package";
  my $image_pkg = $package . '::Image';
  my $font_pkg  = $package . '::Font';
  # Creating new images thus becomes
  my $image   = $image_pkg->new($width,$height);
  # Establish the image output type
  my $image_type;
  if ($package = 'GD::SVG') {
    $image_type = 'svg';
  } else {
    $image_type = 'png';
  }

Finally, you should change all GD::Image and GD::Font references to $image_pkg-> and $font_pkg->, respectively.

  GD::Image->new()   becomes   $image_pkg->new()
  GD::Font->Large()  becomes   $font_pkg->Large()

The GD::Polygon and GD::Polyline classes work with GD::SVG without modification.

If you make heavy use of GD's exported methods, it may also be necessary to add () to the endo of method names to avoide bareword compilation errors. That's the price you pay for using exported functions!

IMPORTANT NOTES

GD::SVG does not directly generate SVG, but instead relies upon SVG.pm. It is not intended to supplant SVG.pm. Furthermore, since GD::SVG is, in essence an API to an API, it may not be suitable for applications where speed is of the essence. In these cases, GD::SVG may provide a short-term solution while scripts are re-written to enable more direct output of SVG.

Many of the GD::SVG methods accept additional parameters (which are in turn reflected in the SVG.pm API) that are not supported in GD. Look through the remainder of this document for options on specific In addition, several functions have yet to be mapped to SVG.pm calls. Please see the section below regarding regarding GD functions that are missing or altered in GD::SVG.

A similar module (SVG::GD) implements a similar wrapper around GD. Please see the section at the bottom of this document that compares GD::SVG to SVG::GD.

PREREQUISITES

GD::SVG requires the Ronan Oger's SVG.pm module, Lincoln Stein's GD.pm module, libgd and its dependencies.

GENERAL DIFFICULTIES IN TRANSLATING GD TO SVG

These are the primary weaknesses of GD::SVG.

Each element in an SVG image requires a unique identifier. In general, GD::SVG handles this by automatically generating unique random numbers. In addition to the typical parameters for GD methods, GD::SVG methods allow a user to pass an optional id parameter for naming the object.
You must change direct calls to the classes that GD invokes:
GD::Image->new() should be changed to GD::SVG::Image->new()

See the documentation above for how to dynamically switch between packages.

As SVG documents are not inherently aware of their canvas, the flood fill methods are not currently supported.
Although setPixel() works as expected, its counterpart getPixel() is not supported. I plan to support this method in a future release.
GD::SVG works only with scripts that generate images directly in the code using the GD->new(height,width) approach. newFrom() methods are not currently supported.
Any functions passed gdTiled objects will die.
Calls to the gdStyled and gdBrushed functions via a rather humorous kludge (and simplification). Depending on the complexity of the brush, they may behave from slightly differently to radically differently from their behavior under GD. You have been warned. See the documentation sections for the methods that set these options (setStyle(), setBrush(), and setTransparent()).

See below for a full list of methods that have not yet been implemented.

WHEN THINGS GO WRONG

GD is a complicated module. Translating GD methods into those required to draw in SVG are not always direct. You may or may not get the output you expect. In general, some tweaking of image parameters (like text height and width) may be necessary.

If your script doesn't work as expected, first check the list of methods that GD::SVG provides. Due to differences in the nature of SVG images, not all GD methods have been implemented in GD::SVG.

If your image doesn't look as expected, try tweaking specific aspects of image generation. In particular, check for instances where you calculate dimensions of items on the fly like font->height. In SVG, the values of fonts are defined explicitly.

GD FUNCTIONS MISSING FROM GD::SVG

The following GD functions have not yet been incorporated into GD::SVG. If you attempt to use one of these functions (and you have enabled debug warnings via the new() method), GD::SVG will print a warning to STDERR.

  Creating image objects:
    GD::Image->newPalette([$width,$height])
    GD::Image->newTrueColor([$width,$height])
    GD::Image->newFromPng($file, [$truecolor])
    GD::Image->newFromPngData($data, [$truecolor])
    GD::Image->newFromJpeg($file, [$truecolor])
    GD::Image->newFromJpegData($data, [$truecolor])
    GD::Image->newFromXbm($file)
    GD::Image->newFromWMP($file)
    GD::Image->newFromGd($file)
    GD::Image->newFromGdData($data)
    GD::Image->newFromGd2($file)
    GD::Image->newFromGd2Data($data)
    GD::Image->newFromGd2Part($file,srcX,srcY,width,height)
    GD::Image->newFromXpm($filename)
  Image methods:
    $gddata   = $image->gd
    $gd2data  = $image->gd2
    $wbmpdata = $image->wbmp([$foreground])
  Color control methods:
    $image->colorAllocateAlpha()
    $image->colorClosest()
    $image->colorClosestHWB()
    $image->getPixel()
    $image->transparent()
  Special Colors:
    $image->setBrush() (semi-supported, with kludge)
    $image->setStyle() (semi-supported, with kludge)
    gdTiled
    $image->setAntialiased()
    gdAntiAliased()
    $image->setAntiAliasedDontBlend()
  Drawing methods:
    $image->dashedLine()
    $image->fill()
    $image->fillToBorder()
  Image copying methods
    None of the image copying methods are yet supported
  Image transformation methods
    None of the image transformation methods are yet supported
  Character and string drawing methods
     $image->stringUp()  - incompletely supported - broken
     $image->charUp()
     $image->stringFT()
  Alpha Channels
    $image->alphaBlending()
    $image->saveAlpha()
  Miscellaneous image methods
    $image->isTrueColor()
    $image->compare($image2)
    $image->clip()
    $image->boundsSafe()
  GD::Polyline
    Supported without modifications
  Font methods:
    $font->nchars()
    $font->offset()

GROUPING FUNCTIONS GD::SVG

GD::SVG supports three additional methods that provides the ability to recursively group objects:

$this->startGroup([$id,\%style]), $this->endGroup()
These methods start and end a group in a procedural manner. Once a group is started, all further drawing will be appended to the group until endGroup() is invoked. You may optionally pass a string ID and an SVG styles hash to startGroup.
$group = $this->newGroup([$id,\%style])
This method returns a GD::Group object, which has all the behaviors of a GD::SVG object except that it draws within the current group. You can invoke this object's drawing methods to draw into a group. The group is closed once the object goes out of scope. While the object is open, invoking drawing methods on the parent GD::SVG object will also draw into the group until it goes out of scope.

Here is an example of using grouping in the procedural way:

 use GD::SVG;
 my $img   = GD::SVG::Image->new(500,500);
 my $white = $img->colorAllocate(255,255,255);
 my $black = $img->colorAllocate(0,0,0);
 my $blue  = $img->colorAllocate(0,0,255);
 my $red   = $img->colorAllocate(255,0,0);
 $img->startGroup('circle in square');
 $img->rectangle(100,100,400,400,$blue);
 $img->startGroup('circle and boundary');
 $img->filledEllipse(250,250,200,200,$red);
 $img->ellipse(250,250,200,200,$black);
 $img->endGroup;
 $img->endGroup;
 
 print $img->svg;
    

Here is an example of using grouping with the GD::Group object:

  ...
 my $g1 = $img->newGroup('circle in square');
 $g1->rectangle(100,100,400,400,$blue);
 my $g2 = $g1->startGroup('circle and boundary');
 $g2->filledEllipse(250,250,200,200,$red);
 $g2->ellipse(250,250,200,200,$black);
 print $img->svg;
    

Finally, here is a fully worked example of using the GD::Simple module to make the syntax cleaner:

 #!/usr/bin/perl
    
 use strict;
 use GD::Simple;
 GD::Simple->class('GD::SVG');
 my $img = GD::Simple->new(500,500);
 $img->bgcolor('white');
 $img->fgcolor('blue');
 my $g1 = $img->newGroup('circle in square');
 $g1->rectangle(100,100,400,400);
 $g1->moveTo(250,250);
 my $g2 = $g1->newGroup('circle and boundary');
 $g2->fgcolor('black');
 $g2->bgcolor('red');
 $g2->ellipse(200,200);
 print $img->svg;
    

GD VERSUS GD::SVG METHODS

All GD::SVG methods mimic the naming and interface of GD methods. As such, maintenance of GD::SVG follows the development of both GD and SVG. Much of the original GD documentation is replicated here for ease of use. Subtle differences in the implementation of these methods between GD and GD::SVG are discussed below. In particular, the return value for some GD::SVG methods differs from its GD counterpart.

OBJECT CONSTRUCTORS: CREATING IMAGES

GD::SVG currently only supports the creation of image objects via its new constructor. This is in contrast to GD proper which supports the creation of images from previous images, filehandles, filenames, and data.

$image = GD::SVG::Image->new($height,$width,$debug);
Create a blank GD::SVG image object of the specified dimensions in pixels. In turn, this method will create a new SVG object and store it internally. You can turn on debugging with the GD::SVG specific $debug parameter. This should be boolean true and will cause non-implemented methods to print a warning on their status to STDERR.

GD::SVG::Image METHODS

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.

Image Data Output Methods

GD::SVG implements a single output method, svg()!

$svg = $image->svg();
This returns the image in SVG format. You may then print it, pipe it to an image viewer, or write it to a file handle. For example,

  $svg_data = $image->svg();
  open (DISPLAY,"| display -") || die;
  binmode DISPLAY;
  print DISPLAY $svg_data;
  close DISPLAY;
    

if you'd like to return an inline version of the image (instead of a full document version complete with the DTD), pass the svg() method the 'inline' flag:

  $svg_data = $image->svg(-inline=>'true');
    

Calling the other standard GD image output methods (eg jpeg,gd,gd2,png) on a GD::SVG::Image object will cause your script to exit with a warning.

Color Control

These methods allow you to control and manipulate the color table of a GD::SVG image. In contrast to GD which uses color indices, GD::SVG passes stringified RGB triplets as colors. GD::SVG, however, maintains an internal hash structure of colors and colored indices in order to map GD functions that manipulate the color table. This typically requires behind-the-scenes translation of these stringified RGB triplets into a color index.

$stringified_color = $image->colorAllocate(RED,GREEN,BLUE)
Unlike GD, colors need not be allocated in advance in SVG. Unlike GD which returns a color index, colorAllocate returns a formatted string compatible with SVG. Simultaneously, it creates and stores internally a GD compatible color index for use with GD's color manipulation methods.

  returns: "rgb(RED,GREEN,BLUE)"
    
$index = $image->colorAllocateAlpha()
NOT IMPLEMENTED
$image->colorDeallocate($index)
Provided with a color index, remove it from the color table.
$index = $image->colorClosest(red,green,blue)
This returns the index of the color closest in the color table to the red green and blue components specified. This method is inherited directly from GD.

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

NOT IMPLEMENTED

$index = $image->colorClosestHWB(red,green,blue)
NOT IMPLEMENTED
$index = $image->colorExact(red,green,blue)
Retrieve the color index of an rgb triplet (or -1 if it has yet to be allocated).

NOT IMPLEMENTED

$index = $image->colorResolve(red,green,blue)
NOT IMPLEMENTED
$colors_total = $image->colorsTotal()
Retrieve the total number of colors indexed in the image.
$index = $image->getPixel(x,y)
NOT IMPLEMENTED
($red,$green,$blue) = $image->rgb($index)
Provided with a color index, return the RGB triplet. In GD::SVG, color indexes are replaced with actual RGB triplets in the form "rgb($r,$g,$b)".
$image->transparent($colorIndex);
Control the transparency of individual colors.

NOT IMPLEMENTED

Special Colors

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. GD::SVG offers limited support for these methods.

$image->setBrush($brush) (KLUDGE ALERT)
In GD, one can draw lines and shapes using a brush pattern. Brushes are just images that you can create and manipulate in 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 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.

  # Via GD, this is how one would set a Brush
  $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
    

GD::SVG offers limited support for setBrush (and the corresponding gdBrushed methods) - currently only in the shapes of squares. Internally, GD::SVG extracts the longest dimension of the image using the getBounds() method. Next, it extracts the second color set, assuming that to be the foreground color. It then re-calls the original drawing method with these new values in place of the gdBrushed. See the private _distill_gdSpecial method for the internal details of this operation.

$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)
setStyle() and gdStyled() are partially supported in GD::SVG. GD::SVG determines the alternating pattern of dashes, treating the first unique color encountered in the array as on, the second as off and so on. The first color in the array is then used to draw the actual line.
NOT IMPLEMENTED
The GD special color gdStyled is partially implemented in GD::SVG. Only the first color will be used to generate the dashed pattern specified in setStyle(). See setStyle() for additional information.
$image->setAntiAliased($color)
NOT IMPLEMENTED
NOT IMPLEMENTED
$image->setAntiAliasedDontBlend($color,[$flag])
NOT IMPLEMENTED

Drawing Commands

$image->setPixel($x,$y,$color)
Set the corresponding pixel to the given color. GD::SVG implements this by drawing a single dot in the specified color at that position.
$image->line(x1,y1,x2,y2,color);
Draw a line between the two coordinate points with the specified color. Passing an optional id will set the id of that SVG element. GD::SVG also supports drawing with the special brushes - gdStyled and gdBrushed - although these special styles are difficult to replicate precisley in GD::SVG.
$image->dashedLine($x1,$y1,$x2,$y2,$color);
NOT IMPLEMENTED
$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. You may also draw with the special colors gdBrushed and gdStyled.
$image->filledRectangle($x1,$y1,$x2,$y2,$color);
filledRectangle is a GD specific method with no direct equivalent in SVG. GD::SVG translates this method into an SVG appropriate method by passing the filled color parameter as a named 'filled' parameter to SVG. Drawing with the special colors is also permitted. See the documentation for the line() method for additional details.

   GD call:
     $img->filledRectangle($x1,$y1,$x2,$y2,$color);
  
   SVG call:
     $img->rectangle(x=> $x1,y=> $y1,
                     width  => $x2-$x1,
                     height => $y2-$y1,
                     fill   => $color
    
$image->polygon($polygon,$color);
This draws a polygon with the specified color. The polygon must be created first (see "Polygons" below). The polygon must have at least three vertices. If the last vertex doesn't close the polygon, the method will close it for you. Both real color indexes and the special colors gdBrushed, gdStyled and gdStyledBrushed can be specified. See the documentation for the line() method for additional details.

  $poly = new GD::Polygon;
  $poly->addPt(50,0);
  $poly->addPt(99,99);
  $poly->addPt(0,99);
  $image->polygon($poly,$blue);
    
$image->filledPolygon($polygon,$color);
This draws a polygon filled with the specified color. Drawing with the special colors is also permitted. See the documentation for the line() method for additional details.

  # 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
  $image->filledPolygon($poly,$peachpuff);
    
$image->filledPolygon($polygon,$color);
This draws a polygon filled with the specified color. Drawing with the special colors is also permitted. See the documentation for the line() method for additional details.

  # 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
  $image->filledPolygon($poly,$peachpuff);
    
$image->polyline(polyline,color)
  $image->polyline($polyline,$black)
    

This draws a polyline with the specified color. Both real color indexes and the special colors gdBrushed, gdStyled and gdStyledBrushed can be specified.

Neither the polyline() method or the polygon() method are very picky: you can call either method with either a GD::Polygon or a GD::Polyline. The method determines if the shape is "closed" or "open" as drawn, not the object type.

$image->polydraw(polything,color)
        $image->polydraw($poly,$black)
    

This method draws the polything as expected (polygons are closed, polylines are open) by simply checking the object type and calling either $image->polygon() or $image->polyline().

$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, respectively. filledEllipse() is like ellipse() except that the former produces filled versions of the ellipse. Drawing with the special colors is also permitted. See the documentation for the line() method for additional details.
$image->arc($cy,$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 degrees from 0 to 360. Zero is at the top of the ellipse, and angles increase clockwise. To specify 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.

Internally, arc() calls the ellipse() method of SVG.pm. Drawing with the special colors is also permitted. See the documentation for the line() method for additional details.

Currently, true arcs are NOT supported, only those where the start and end equal 0 and 360 respectively resulting in a closed arc.

$image->filledArc($cx,$cy,$width,$height,$start,$end,$color [,$arc_style])
This method is like arc() except that it colors in 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."

Using these special styles, you can easily draw bordered ellipses and circles.

# Create the filled shape: $image->filledArc($x,$y,$width,$height,0,360,$fill); # Now border it. $image->filledArc($x,$y,$width,$height,0,360,$color,gdNoFill);

$image->fill();
NOT IMPLEMENTED
$image->fillToBorder()
NOT IMPLEMENTED

Image Copying Methods

The basic copy() command is implemented in GD::SVG. You can copy one GD::SVG into another GD::SVG, or copy a GD::Image or GD::Simple object into a GD::SVG, thereby embedding a pixmap image into the SVG image.

All other image copying methods are unsupported, and if your script calls one of the following methods, your script will die remorsefully with a warning. With sufficient demand, I might try to implement some of these methods. For now, I think that they are beyond the intent of GD::SVG.

  $image->clone()
  $image->copyMerge()
  $image->copyMergeGray()
  $image->copyResized()
  $image->copyResampled()
  $image->trueColorToPalette()

Image Transfomation Commands

None of the image transformation commands are implemented in GD::SVG. If your script calls one of the following methods, your script will die remorsefully with a warning. With sufficient demand, I might try to implement some of these methods. For now, I think that they are beyond the intent of GD::SVG.

  $image = $sourceImage->copyRotate90()
  $image = $sourceImage->copyRotate180()
  $image = $sourceImage->copyRotate270()
  $image = $sourceImage->copyFlipHorizontal()
  $image = $sourceImage->copyFlipVertical()
  $image = $sourceImage->copyTranspose()
  $image = $sourceImage->copyReverseTranspose()
  $image->rotate180()
  $image->flipHorizontal()
  $image->flipVertical()

Character And String Drawing

GD allows you to draw characters and strings, either in normal horizon- tal orientation or rotated 90 degrees. In GD, these routines use a GD::Font object. Internally, GD::SVG mimics the behavior of GD with respect to fonts in a very similar manner, using instead a GD::SVG::Font object described in more detail below.

GD's font handling abilities are not as flexible as SVG and it does not allow the dynamic creation of fonts, instead exporting five available fonts as global variables: gdGiantFont, gdLargeFont, gdMediumBoldFont, gdSmallFont and gdTinyFont. GD::SVG also exports these same global variables but establishes them in a different manner using constant variables to establish the font family, font height and width of these global fonts. These values were chosen to match as closely as possible GD's output. If unsatisfactory, adjust the constants at the top of this file. In all subroutines below, GD::SVG passes a generic GD::SVG::Font object in place of the exported font variables.

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

  $myImage->string(gdSmallFont,2,10,"Peachy Keen",$peach);
    
$image->stringUp($font,$x,$y,$string,$color)
Same as the previous example, except that it 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 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. Neither is SVG, which simply calls the string() method internally.
@bounds = $image->stringFT($fgcolor,$font- name,$ptsize,$angle,$x,$y,$string)
@bounds = $image->stringFT($fgcolor,$font- name,$ptsize,$angle,$x,$y,$string,\%options)
In GD, these methods use TrueType to draw a scaled, antialiased strings using the TrueType font of your choice. GD::SVG can handle this directly generating by calling the string() method internally.

  The arguments are as follows:
  fgcolor    Color index to draw the string in
  fontname   An absolute path to the TrueType (.ttf) font file
  ptsize     The desired point size (may be fractional)
  angle      The rotation angle, in radians
  x,y        X and Y coordinates to start drawing the string
  string     The string itself
    

GD::SVG attempts to extract the name of the font from the pathname supplied in the fontname argument. If it fails, Helvetica will be used instead.

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)
    

This from the GD documentation (not yet implemented in GD::SVG):

An optional 8th argument allows you to pass a hashref of options to stringFT(). Two hashkeys are recognized: linespacing, if present, controls the spacing between lines of text. charmap, if 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 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.

  $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 the libgd library.

$hasfontconfig = $image->useFontConfig($flag)
Call useFontConfig() with a value of 1 in order to enable support for fontconfig font patterns (see stringFT). Regardless of the value of $flag, this method will return a true value if the fontconfig library is present, or false otherwise.

NOT IMPLEMENTED

Alpha Channels

$image->alphaBlending($blending)
NOT IMPLEMENTED
$image->saveAlpha($saveAlpha)
NOT IMPLEMENTED

Miscellaneous Image Methods

$image->interlaced([$flag])
NOT IMPLEMENTED
($width,$height) = $image->getBounds()
getBounds() returns the height and width of the image.
$is_truecolor = $image->isTrueColor()
NOT IMPLEMENTED
$flag = $image1->compare($image2)
NOT IMPLEMENTED
$image->clip($x1,$y1,$x2,$y2) ($x1,$y1,$x2,$y2) = $image->clip
NOT IMPLEMENTED
$flag = $image->boundsSafe($x,$y)
NOT IMPLEMENTED

GD::SVG::Polygon METHODS

SVG is much more adept at creating polygons than GD. That said, GD does provide some rudimentary support for polygons but must be created as seperate objects point by point.

$poly = GD::SVG::Polygon->new
Create an empty polygon with no vertices.

  $poly = new GD::SVG::Polygon;
    
$poly->addPt($x,$y)
Add point (x,y) to the polygon.

  $poly->addPt(0,0);
  $poly->addPt(0,50);
  $poly->addPt(25,25);
    
($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 to set 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);
    

NOT IMPLEMENTED

$vertex_count = $poly->length()
Return the number of vertices in the polygon.
@vertices = $poly->vertices()
Return a list of all the verticies in 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(",",@$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 the polygon down and to the right. Returns the number of vertices affected.

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

NOT IMPLEMENTED

$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 the center of the polygon to position (0,0) before you scale, then move it back to its previous position.

NOT IMPLEMENTED

$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.

NOT IMPLEMENTED

GD::Polyline

Please see GD::Polyline for information on creating open polygons and splines.

GD::SVG::Font METHODS

NOTE: The object-oriented implementation to font utilites is not yet supported.

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.

GD::SVG replicates the internal fonts of GD by hardcoding fonts which resemble the design and point size of the original. Each of these fonts is available both as an imported global (e.g. gdSmallFont) and as a package method (e.g. GD::Font->Small).

This is a tiny, almost unreadable font, 5x8 pixels wide.
This is the basic small font, "borrowed" from a well known public domain 6x12 font.
This is a bold font intermediate in size between the small and large fonts, borrowed from a public domain 7x13 font;
This is the basic large font, "borrowed" from a well known public domain 8x16 font.
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 the font.

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

NOT IMPLEMENTED

$font->offset()
This returns the ASCII value of the first character in the font
$width = $font->width
$height = $font->height
These return the width and height of the font.

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

REAL WORLD EXAMPLES

The Bio::Graphics package of the BioPerl project makes use of GD::SVG to export SVG graphics.

  http://www.bioperl.org/
    
The Generic Genome Browser (GBrowse) utilizes Bio::Graphics and enables SVG dumping of genomics views. You can see a real-world example of SVG output from GBrowse at WormBase:

  http://www.wormbase.org/cgi-bin/gbrowse/
    

Further information about the Generic Genome Browser is available at the Generic Model Organism Project home page:

  http://www.gmod.org/
    
I've also prepared a number of comparative images at my website (shameless plug, hehe):

  http://www.toddot.net/projects/GD-SVG/
    

INTERNAL METHODS

The following internal methods are private and documented only for those wishing to extend the GD::SVG interface.

_distill_gdSpecial()
When a drawing method is passed a stylized brush via gdBrushed, the internal _distill_gdSpecial() method attempts to make sense of this by setting line thickness and foreground color. Since stylized brushes are GD::SVG::Image objects, it does this by fetching the width of the image using the getBounds method. This width is then used to setThickness. The last color set by colorAllocate is then used for the foreground color.

In setting line thickness, GD::SVG temporarily overrides any previously set line thickness. In GD, setThickness is persistent through uses of stylized brushes. To accomodate this behavior, _distill_gdSpecial() temporarily stores the previous line_thickness in the $self->{previous_line_thickness} flag.

_reset()
The _reset() method is used to restore persistent drawing settings between uses of stylized brushes. Currently, this involves

  - restoring line thickness
    

IMPORTANT NOTE! GD::SVG / SVG::GD

A second module (SVG::GD), written by Ronan Oger also provides similar functionality as this module. Ronan and I are concurrently developing these modules with an eye towards integrating them in the future. In principle, the primary difference is that GD::SVG aims to generate SVG and SVG only. That is, it:

  1. Does not store an internal representation of the GD image
  2. Does not enable JPG, PNG, OR SVG output from a single pass
     through data
  3. Only occasioanally uses inherited methods from GD

Instead GD::SVG depends on the user to choose which output format they would like in advance, "use"ing the appropriate module for that output. As described at the start of this document, module selection between GD and GD::SVG can be made dynamically using eval statements and variables for the differnet classes that GD and GD::SVG create.

There is a second reason for not maintaining a double representation of the data in GD and SVG format: SVG documents can quickly become very large, especially with large datasets. In cases where scripts are primarily generating png images in a server environment and would only occasionally need to export SVG, gernerating an SVG image in parallel would result in an unacceptable performance hit.

Thus GD::SVG aims to be a plugin for existing configurations that depend on GD but would like to take advantage of SVG output.

SVG::GD, on the other hand, aims to tie in the raster-editing ability of GD with the power of SVG output. In part, it aims to do this by inheriting many methods from GD directly and bringing them into the functional space of GD. This makes SVG::GD easier to set up initially (simply by adding the "use SVG::GD" below the "use GD" statement of your script. GD::SVG sacrfices this initial ease-of-setup for more targeted applications.

ACKNOWLEDGEMENTS

Lincoln Stein, my postdoctoral mentor, author of GD.pm, and all around Perl stud. Ronan Oger, author of SVG.pm conceptualized and implemented another wrapper around GD at about the exact same time as this module. He also provided helpful discussions on implementing GD functions into SVG. Oliver Drechsel and Marc Lohse provided patches to actually make the stringUP method functional.

AUTHOR

Todd Harris, PhD <harris@cshl.org>

COPYRIGHT AND LICENSE

Copyright @ 2003-2005 Todd Harris and the Cold Spring Harbor Laboratory

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

SEE ALSO

GD, SVG, SVG::Manual, SVG::DOM

2020-07-29 perl v5.30.3