GD#

📦 std

Perl bindings for libgd, the GD graphics library.

This is the GD module, version 2.91 of the CPAN API: the same packages, methods, arguments and return values that Perl code written against GD already expects. Drawing goes to the libgd.so.3 installed on the machine, which is located when the module is loaded; if that library is absent, use GD dies with a message naming the distribution package to install, as it does under a perl whose GD was never built.

use GD;

my $im    = GD::Image->new(200, 200, 1);   # 1 = truecolor
my $white = $im->colorAllocate(255, 255, 255);
my $blue  = $im->colorAllocate(0, 0, 255);

$im->filledRectangle(0, 0, 199, 199, $white);
$im->line(0, 0, 199, 199, $blue);

open my $fh, '>', 'out.png' or die $!;
binmode $fh;
print $fh $im->png;

The colour index#

GD’s defining quirk is that you do not draw with a colour, you draw with the integer colorAllocate gives back. On a palette image that integer really is an index into a 256-entry table, and running out of entries makes colorAllocate return -1. On a truecolor image - what you get by passing a true third argument to new - the integer is the packed colour itself and there is no limit, but the API keeps the same shape.

GD::Image#

An image is either palette or truecolor, chosen when you make it, and the difference runs through the whole API:

my $palette   = GD::Image->new(200, 200);      # 256 colours, indexed
my $truecolor = GD::Image->new(200, 200, 1);   # 24-bit + alpha

Drawing#

Note the shapes of the argument lists, which are not uniform and are the usual source of surprise. Rectangles take two corners; arcs and ellipses take a centre plus width and height (not a radius); filledArc adds start and end angles in degrees.

$im->line(0, 0, 199, 199, $blue);
$im->rectangle(10, 10, 60, 60, $blue);          # outline
$im->filledRectangle(70, 10, 120, 60, $red);    # solid
$im->arc(100, 100, 80, 80, 0, 360, $blue);      # centre, w, h, start, end
$im->filledArc(100, 100, 120, 60, 0, 180, $red);
$im->setPixel(5, 5, $blue);
$im->fill(30, 30, $red);                        # flood fill

Polygons are drawn from a GD::Polygon, and the special colour values gdBrushed, gdStyled, gdTiled and gdAntiAliased select the brush, style or tile you set beforehand instead of a plain colour.

Reading and writing#

Output methods return the encoded bytes rather than writing a file, so you print them yourself:

open my $fh, '>', 'out.png' or die $!;
binmode $fh;
print $fh $im->png;             # or ->jpeg($quality), ->gif, ->webp

Reading goes through newFrom<Format> for a filehandle or newFrom<Format>Data for bytes you already have. Which formats work depends on how the installed libgd was built. GD::Image->supported lists them, GD::supportsFileType('photo.webp') answers for one file name, and the methods of a format this libgd lacks do not exist, so GD::Image->can('newFromTiff') is a test too. A GD built from source settles that when it is compiled; here it is settled when the module is loaded, by the libgd found then.

A reader dies when libgd cannot decode what it was given. The PNG, JPEG and TIFF readers, and newFromBmpData and newFromWBMPData, return palette images unless you pass a true final argument - GD::Image->newFromPngData($bytes, 1) - or have made truecolor the default with GD::Image->trueColor(1).

GD::Font - the built-in bitmap fonts#

libgd ships five fixed-size bitmap fonts, reached as class methods:

my $font = GD::Font->Small;
$image->string($font, 10, 10, 'hello', $black);

The five are Tiny, Small, MediumBold, Large and Giant, and GD also exports them as the functions gdTinyFont, gdSmallFont, gdMediumBoldFont, gdLargeFont and gdGiantFont, which is the spelling most existing code uses.

A font knows its own metrics: $font->width and $font->height are the size of one character cell, which is what you need to work out where a string will land, and $font->nchars and $font->offset describe which characters it covers.

These fonts are fixed-width bitmaps and cannot be scaled or rotated. For scalable text, use $image->stringFT, which draws with FreeType from a TrueType file at any size and angle.

What is native and what is Perl#

GD is a large module whose pure-Perl half does real work: GD::Polygon, GD::Polyline and GD::Simple are Perl, and so is the filehandle plumbing behind newFromPng and friends. That half runs here exactly as it does on perl5, from the module’s own source; only the parts that were C are native. So GD::Simple->new(...)->moveTo(...) behaves as its own documentation says, because it IS its own code.

Differences from upstream#

Each where XS GD crashes, reads memory it does not own, or refuses what libgd can do (t/64-auto-ffi/332-gd-or-better.t):

  • cloneImage after filledPolygon copies the image, where libgd’s gdImageClone crashes on such an image.

  • A newFrom* reader or an affine* constructor called with an argument short (through &, past the prototype) croaks its usage; GD.xs reads the missing argument from beyond the stack.

  • scatterColor treats a colour that is not an integer as 0, and an empty colour list as no colours; GD.xs passes uninitialised memory for the one and a negative count for the other.

  • The formats are the ones libgd reads, not the ones the module’s build guessed from pkg-config: an XS GD may lack newFromXpm on a libgd that reads XPM.

  • A method on an image whose DESTROY has run, or on the empty copy Storable::dclone makes of an image, croaks “not a live GD::Image”; GD.xs passes the NULL pointer to libgd.

  • GD::Font->load refuses a font file whose header gives no characters or a negative size, as it refuses a file it cannot read; GD.xs trusts the header.

Modules#

  • GD::Group - Simple object for recursive grouping

  • GD::Image - Image class for the GD image library

  • GD::Polygon - Polygon class for the GD image library

  • GD::Polyline - Polyline object and Polygon utilities (including splines) for use with GD

  • GD::Simple - Simplified interface to GD library

Functions#

Library information#

VERSION_STRING#

The version of the libgd actually loaded, as a string such as "2.3.3" (gd.h’s GD_VERSION_STRING). This is a run-time answer: it describes the library on this machine, not the one anything was built against. The version of the Perl module is $GD::VERSION.

LIBGD_VERSION#

The version of the libgd actually loaded, as one number: major, then minor and release as two decimal places each, so that versions compare numerically. libgd 2.3.3 is 2.0303.

supportsFileType#

True when the loaded libgd can read, or with a true second argument write, the image file named by its first argument.