gd 1.3

gd 1.3

1

A graphics library for fast GIF creation



Follow this link to the 3latest versionof this document.



Table of Contents

%

2Up to the Boutell.Com, Inc. Home Page7

Credits and license terms



CIn order to resolve any possible confusion regarding the authorshipBof gd, the following copyright statement covers all of the authorsDwho have required such a statement. Although his LZW compressionEcode no longer appears in gd, the authors wish to thank David Rowley Gfor the original LZW-based GIF compression code, which has been removedGdue to patent concerns. If you are aware of any oversights)in this copyright notice, please contact DThomas Boutell who will be !pleased to correct them.

%COPYRIGHT STATEMENT FOLLOWS THIS LINE
?Portions copyright 1994, 1995, 1996, 1997, 1998, by Cold SpringBHarbor Laboratory. Funded under Grant P41-RR02188 by the National Institutes of Health.

9Portions copyright 1996, 1997, 1998, by Boutell.Com, Inc.

CGIF decompression code copyright 1990, 1991, 1993, by David Koblas (koblas@netcom.com). 

GNon-LZW-based GIF compression code copyright 1998, by Hutchison Avenue NSoftware Corporation (http://www.hasc.com/, info@hasc.com). 

EPermission has been granted to copy and distribute gd in any Gcontext, including a commercial application, provided that this notice @is present in user-accessible supporting documentation.

NThis does not affect your ownership of the derived work itself, and the intentBis to assure proper credit for the authors of gd, not to interfere<with your productive use of gd. If you have questions, ask. @"Derived works" includes all programs that utilize the library. 6Credit must be given in user-accessible documentation.

FPermission to use, copy, modify, and distribute this software and its Jdocumentation for any purpose and without fee is hereby granted, provided Hthat the above copyright notice appear in all copies and that both that Acopyright notice and this permission notice appear in supporting Edocumentation. This software is provided "as is" without express or implied warranty.


END OF COPYRIGHT STATEMENT
)

What is gd?



8gd is a graphics library. It allows your code to quickly5draw images complete with lines, arcs, text, multiple=colors, cut and paste from other images, and flood fills, and9write out the result as a .GIF file. This is particularly8useful in World Wide Web applications, where .GIF is theformat used for inline images.

gd is not a paint program. :If you are looking for a paint program, you are looking in=the wrong place. If you are not a programmer, you are lookingin the wrong place.

9gd does not provide for every possible desirable graphics<operation. It is not necessary or desirable for gd to become=a kitchen-sink graphics package, but version 1.3 incorporates@most of the commonly requested features for an 8-bit 2D package.>Support for scalable fonts, and truecolor images, JPEG and PNG?is planned for version 2.0. Version 1.3 was released to correctBlongstanding bugs and provide an LZW-free GIF compression routine.

?

What if I want to use another programminglanguage?

Perl

*gd can also be used from Perl, courtesy ofLincoln Stein'sD:GD.pm library, which uses gd as the basis for a set of>Perl 5.x classes. GD.pm is based on gd 1.1.1 but gd 1.2 shouldbe compatible.

Any Language

AThere are, at the moment, at least three simple interpreters thatFperform gd operations. You can output the desired commands to a simpleBtext file from whatever scripting language you prefer to use, theninvoke the interpreter.

@These packages are based on gd 1.2 as of this writing but should1be compatible with gd 1.3 with minimal tweaking. 

@

What's new in version 1.3?

+Version 1.3 features the following changes:
&
Non-LZW-based GIF compression code
FVersion 1.3 contains GIF compression code that uses simple Run Length IEncoding instead of LZW compression, while still retaining compatibility Lwith normal LZW-based GIF decoders (your browser will still like your GIFs).ELZW compression is patented by Unisys. This is why there have5been no new versions of gd for a long time. THANKS to6Hutchison Avenue Software Corporation for contributing<this code. THE NEW CODE PRODUCES LARGER GIFS AND IS NOT WELL5SUITED TO PHOTOGRAPHIC IMAGES. THIS IS A LEGAL ISSUE.5IT IS NOT A QUESTION OF TECHNICAL SKILL. PLEASE DON'T7COMPLAIN ABOUT THE SIZE OF GIF OUTPUT. THANKS!'
8-bit fonts, and 8-bit font supportA
This improves support for European languages. Thanks are due =to Honza Pazdziora and also to AJan Pazdziora . Also see the provided bdftogd8Perl script if you wish to convert fixed-width X11 fonts to gd fonts.+
16-bit font support (no fonts provided)=
Although no such fonts are provided in the distribution, =fonts containing more than 256 characters should work if the 8gdImageString16 and gdImageStringUp16 routines are used.0
Improvements to the "webgif" example/utilityM
The "webgif" utility is now a slightly more useful application. Thanks toBrian Dowling for this code.;
Corrections to the color resolution field of GIF output
Thanks to Bruno Aureli.
Fixed polygon fills@
A one-line patch for the infamous polygon fill bug, courtesy?of Jim Mason. I believe this fix is sufficient. However, if youCfind a situation where polygon fills still fail to behave properly,Eplease send code that demonstrates the problem, and a fix if-you have one. Verifying the fix is important.
Row-major, not column-major8
Internally, gd now represents the array of pixels as;an array of rows of pixels, rather than an array of columns;of pixels. This improves the performance of compression and>decompression routines slightly, because horizontally adjacent@pixels are now next to each other in memory. This shouldBnot affect properly written gd applications, but applications that>directly manipulate the pixels array will requirechanges.
>

What else do I need to use gd?



ATo use gd, you will need an ANSI C compiler. All popular AWindows 95 and NT C compilers are ANSI C compliant. Any Afull-ANSI-standard C compiler should be adequate. The cc >compiler released with SunOS 4.1.3 is not an ANSI C compiler. :Most Unix users who do not already have gcc should get it.=gcc is free, ANSI compliant and a de facto industry standard.r(Ask your ISP why it is missing.

t;You will also want a GIF viewer, if you do not already have@one for your system, since you will need a good way to check the>results of your work. Any web browser will work, but you might7be happier with a package like Lview Pro for Windows or=Dxv for X. There are GIF viewers available for every graphics-capable5computer out there, so consult newsgroups relevant touyour particular system. 

e-

How do I get gd?

<

By HTTP

t

By FTP

rb

>1

How do I build gd?

a

a@In order to build gd, you must first unpack the archive you have=downloaded. If you are not familiar with tar andn@gunzip (Unix) or ZIP (Windows), pleaseAconsult with an experienced user of your system. Sorry, we cannote-answer questions about basic Internet skills.e

o>Unpacking the archive will produce a directory called "gd1.3".

i

For Unix

aGcd to the gd1.3 directory and examine the Makefile, which LEyou will probably need to change slightly depending on your operatingosystem and your needs.$

For Windows, Mac, Et Cetera

=Create a project using your favorite programming environment.@ICopy all of the gd files to the project directory. Add gd.c oDto your project. Add other source files as appropriate. Learning the@basic skills of creating projects with your chosen C environment is up to you.b

r@Now, to build the demonstration program, just type "make gddemo"Dif you are working in a command-line environment, or build a projectHthat includes gddemo.c if you are using a graphical environment. If all Mgoes well, the program "gddemo" will be compiled and linked without incident.g;Depending on your system you may need to edit the Makefile.=;Understanding the basic techniques of compiling and linkingo%programs on your system is up to you. 

e:You have now built a demonstration program which shows off1the capabilities of gd. To see it in action, type "gddemo".i

r9gddemo should execute without incident, creating the filed9demoout.gif. (Note there is also a file named demoin.gif,n?which is provided in the package as part of the demonstration.)o

i8Display demoout.gif in your GIF viewer. The image should4be 128x128 pixels and should contain an image of the:space shuttle with quite a lot of graphical elements drawn on top of it.t

8(If you are missing the demoin.gif file, the other itemsshould appear anyway.)

t4Look at demoin.gif to see the original space shuttle8image which was scaled and copied into the output image.

sA

gd basics: using gd in your program

p;gd lets you create GIF images on the fly. To use gd in youre9program, include the file gd.h, and link with the libgd.a/;library produced by "make libgd.a", under Unix. Under otherN8operating systems you will add gd.c to your own project.

l.If you want to use the provided fonts, includeEgdfontt.h, gdfonts.h, gdfontmb.h, gdfontl.h and/or gdfontg.h. If you rGare not using the provided Makefile and/or a library-based approach, bel2sure to include the source modules as well in your9project. (They may be too large for 16-bit memory models,e!that is, 16-bit DOS and Windows.).

fFHere is a short example program. (For a more advanced example,Nsee gddemo.c, included in the distribution. gddemo.c is NOT the same program; .it demonstrates additional features!)

c

r#/* Bring in gd library functions */l#include "gd.h"e>/* Bring in standard I/O so we can output the GIF to a file */#include <stdio.h>int main() {	/* Declare the image */)	gdImagePtr im;g	/* Declare an output file */r	FILE *out; 	/* Declare color indexes */	int black;t	int white;n=	/* Allocate the image: 64 pixels across by 64 pixels tall */o9	im = gdImageCreate(64, 64);a?	/* Allocate the color black (red, green and blue all minimum).s7		Since this is the first color in a new image, it will.		be the background color. */lP	black = gdImageColorAllocate(im, 0, 0, 0);	B	/* Allocate the color white (red, green and blue all maximum). */V	white = gdImageColorAllocate(im, 255, 255, 255);		 7	/* Draw a line from the upper left to the lower right,i		using white color index. */cB	gdImageLine(im, 0, 0, 63, 63, white);	A	/* Open a file for writing. "wb" means "write binary", importantd&		under MSDOS, harmless under Unix. */	out = fopen("test.gif", "wb");h)	/* Output the image to the disk file. */d0	gdImageGif(im, out);		/* Close the file. */
	fclose(out);e#	/* Destroy the image in memory. */<2	gdImageDestroy(im);}t
7When executed, this program creates an image, allocatess<two colors (the first color allocated becomes the background:color), draws a diagonal line (note that 0, 0 is the upper1left corner), writes the image to a GIF file, andadestroys the image.e

o The above example program should*give you an idea of how the package works.7gd provides many additional functions, which are listed 7in the following reference chapters, complete with code -snippets demonstrating each. There is also anW)alphabetical index. @

Webgif: a more powerful gd example

>Webgif is a simple utility program to manipulate GIFs from the=command line. It is written for Unix and similar command-lineb>systems, but should be easily adapted for other environments. 9Webgif allows you to set transparency and interlacing andc9output interesting information about the GIF in question.>

o8webgif.c is provided in the distribution. Unix users can6simply type "make webgif" to compile the program. Type8"webgif" with no arguments to see the available options.<

Function and type reference

l"

Types


E
gdImage(TYPE)t
GThe data structure in which gd stores images. agdImageCreate returns Aa pointer to this type, and the other functions expect to receivem7a pointer to this type as their first argument. You may 2read the members sx (size on X axis),:sy (size on Y axis), colorsTotal:(total colors), red (red component of colors;?an array of 256 integers between 0 and 255), greenl8(green component of colors, as above), blueB(blue component of colors, as above), and transparent6(index of transparent color, -1 if none); please do so:using the macros provided. Do NOT set the members directly+from your code; use the functions provided.q
stypedef struct {	unsigned char ** pixels;4	int sx;	int sy;	int colorsTotal;U	int red[gdMaxColors];	int green[gdMaxColors];	int blue[gdMaxColors]; 	int open[gdMaxColors];s	int transparent; 
} gdImage;
?
gdImagePtr (TYPE)o
KA pointer to an image structure. gdImageCreateeAreturns this type, and the other functions expect it as the firste argument.t7
gdFont (TYPE)r
@A font structure. Used to declare the characteristics of a font.APlese see the files gdfontl.c and gdfontl.h for an example of theP:proper declaration of this structure. You can provide your>own font data by providing such a structure and the associated?pixel array. You can determine the width and height of a singleo;character in a font by examining the w and h members of the?structure. If you will not be creating your own fonts, you willuEnot need to concern yourself with the rest of the components of this f structure.
btypedef struct {	/* # of characters in font */	int nchars;:	/* First character is numbered... (usually 32 = space) */	int offset;!	/* Character width and height */ 	int w;	int h;d:	/* Font data; array of characters, one row after another.2		Easily included in code, also easily loaded from		data files. */	char *data;	} gdFont; 
=
gdFontPtr (TYPE)k
AA pointer to a font structure. Text-output functions expect these3>as their second argument, following the >gdImagePtr argument. Two such pointers are declared in the/provided include files gdfonts.h and gdfontl.h.y9
gdPoint (TYPE)
=Represents a point in the coordinate space of the image; useda3by gdImagePolygon ande9gdImageFilledPolygon.a
atypedef struct {        int x, y;a} gdPoint, *gdPointPtr;h
?
gdPointPtr (TYPE) 
?A pointer to a gdPoint structure; passede>as an argument to gdImagePolygon=and gdImageFilledPolygon.m
oO

Image creation, destruction, loading and saving

y
6
gdImageCreate(sx, sy) (FUNCTION)
>gdImageCreate is called to create images. Invoke gdImageCreate?with the x and y dimensions of the desired image. gdImageCreateeDreturns a gdImagePtr to the new image, or NULL if unable tot:allocate the image. The image must eventually be destroyed5using gdImageDestroy().h
s... inside a function ...e(gdImagePtr im;im = gdImageCreate(64, 64);h/* ... Use the image ... */1gdImageDestroy(im);s
F
gdImageCreateFromGif(FILE *in) (FUNCTION))
EgdImageCreateFromGif is called to load images from GIF format files. EInvoke gdImageCreateFromGif with an already opened pointer to a file containing the desired image. gdImageCreateFromGifIreturns a gdImagePtr to the new image, or NULL lGif unable to load the image (most often because the file is corrupt or nEdoes not contain a GIF image). gdImageCreateFromGif does not <close the file. You can inspect the sx and sy members of theCimage to determine its size. The image must eventually be destroyedu5using gdImageDestroy().y
a(gdImagePtr im;... inside a function ...j	FILE *in;min = fopen("mygif.gif", "rb");im = gdImageCreateFromGif(in);fclose(in);./* ... Use the image ... */l1gdImageDestroy(im);e
D
gdImageCreateFromGd(FILE *in) (FUNCTION)a
CgdImageCreateFromGd is called to load images from gd format files. uInvoke gdImageCreateFromGdEwith an already opened pointer to a file containing the desired imagegDin the gd file format, which is specific to Hgd and intended for very fast loading. (It is not intended for 'compression; for compression, use GIF.)wgdImageCreateFromGdeIreturns a gdImagePtr to the new image, or NULL CGif unable to load the image (most often because the file is corrupt or gJdoes not contain a gd format image). gdImageCreateFromGd does not<close the file. You can inspect the sx and sy members of theCimage to determine its size. The image must eventually be destroyed 5using gdImageDestroy().u
... inside a function ...o(gdImagePtr im;	FILE *in;5in = fopen("mygd.gd", "rb");im = gdImageCreateFromGd(in);gfclose(in); /* ... Use the image ... */R1gdImageDestroy(im); 
F
gdImageCreateFromXbm(FILE *in) (FUNCTION) 
BgdImageCreateFromXbm is called to load images from X bitmap format"files. Invoke gdImageCreateFromXbmGwith an already opened pointer to a file containing the desired image. gdImageCreateFromXbmIreturns a gdImagePtr to the new image, or NULL RGif unable to load the image (most often because the file is corrupt or (Fdoes not contain an X bitmap format image). gdImageCreateFromXbm does Inot close the file. You can inspect the sx and sy members of theICimage to determine its size. The image must eventually be destroyedh5using gdImageDestroy().o
a... inside a function ...i(gdImagePtr im;	FILE *in;cin = fopen("myxbm.xbm", "rb");im = gdImageCreateFromXbm(in);fclose(in);#/* ... Use the image ... */.1gdImageDestroy(im); 
Z
gdImageDestroy(gdImagePtr im) (FUNCTION)=
gdImageDestroy is used to free the memory associated withl:an image. It is important to invoke gdImageDestroy before 0exiting your program or assigning a new image to0a gdImagePtr variable.
P... inside a function ... (gdImagePtr im;8im = gdImageCreate(10, 10);/* ... Use the image ... */v/* Now destroy it */1gdImageDestroy(im);<

p-void gdImageGif(gdImagePtr im, FILE *out)a(FUNCTION) 
7gdImageGif outputs the specified image to the specifiedhCfile in GIF format. The file must be open for writing. Under MSDOS,e4it is important to use "wb" as opposed to simply "w"7as the mode when opening the file, and under Unix there>8is no penalty for doing so. gdImageGif does not%close the file; your code must do so. 
n... inside a function ...i(gdImagePtr im;int black, white;"
FILE *out;/* Create the image */:im = gdImageCreate(100, 100);/* Allocate background */TTwhite = gdImageColorAllocate(im, 255, 255, 255);/* Allocate drawing color */Nblack = gdImageColorAllocate(im, 0, 0, 0);/* Draw rectangle */JgdImageRectangle(im, 0, 0, 99, 99, black);%/* Open output file in binary mode */aout = fopen("rect.gif", "wb");/* Write GIF */cgdImageGif(im, out);/* Close file */fclose(out);/* Destroy image */01gdImageDestroy(im); 

,void gdImageGd(gdImagePtr im, FILE *out)(FUNCTION) 
6gdImageGd outputs the specified image to the specifiedCfile in the gd image format. The file must Abe open for writing. Under MSDOS, it is important to use "wb" as *Copposed to simply "w" as the mode when opening the file, and under oCUnix there is no penalty for doing so. gdImageGif does notd%close the file; your code must do so.m

<The gd image format is intended for fast reads and writes of7images your program will need frequently to build otherFCimages. It is not a compressed format, and is not intendedrfor general use.

h... inside a function ...A(gdImagePtr im;int black, white;o
FILE *out;/* Create the image */:im = gdImageCreate(100, 100);/* Allocate background */ Twhite = gdImageColorAllocate(im, 255, 255, 255);/* Allocate drawing color */Nblack = gdImageColorAllocate(im, 0, 0, 0);/* Draw rectangle */JgdImageRectangle(im, 0, 0, 99, 99, black);%/* Open output file in binary mode */tout = fopen("rect.gd", "wb");t/* Write gd format file */gdImageGd(im, out);/* Close file */fclose(out);/* Destroy image */t1gdImageDestroy(im);l

/0

Drawing Functions


{
void gdImageSetPixel(gdImagePtr im, int x, int y, int color) (FUNCTION) mH
gdImageSetPixel sets a pixel to a particular color index. Always useEthis function or one of the other drawing functions to access pixels;tIdo not access the pixels of the gdImage structure l directly.A
#... inside a function ...>(gdImagePtr im;
int black;
int white;:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	eA/* Allocate the color white (red, green and blue all maximum). */dUwhite = gdImageColorAllocate(im, 255, 255, 255);	o"/* Set a pixel near the center. */#gdImageSetPixel(im, 50, 50, white);/E/* ... Do something with the image, such as saving it to a file... */;/* Destroy it */1gdImageDestroy(im);/
h
void gdImageLine(gdImagePtr im, int x1, int y1, int x2, int y2, int color)(FUNCTION) 
LgdImageLine is used to draw a line between two endpoints (x1,y1 and x2, y2).FThe line is drawn using the color index specified. Note that the colorIindex can be an actual color returned by gDgdImageColorAllocate or one of gdStyled,AgdBrushed or egdStyledBrushed.
A... inside a function ...m(gdImagePtr im;
int black;
int white;:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	iA/* Allocate the color white (red, green and blue all maximum). */)Uwhite = gdImageColorAllocate(im, 255, 255, 255);	gG/* Draw a line from the upper left corner to the lower right corner. */g%gdImageLine(im, 0, 0, 99, 99, white);GE/* ... Do something with the image, such as saving it to a file... */ /* Destroy it */1gdImageDestroy(im);o
t
void gdImageDashedLine(gdImagePtr im, int x1, int y1, int x2, int y2, int color)(FUNCTION) 
HgdImageDashedLine is provided solely for backwards compatibilityB with gd 1.0. New programs should draw dashed lines usingBthe normal gdImageLine function and the<new gdImageSetStyle function.

FgdImageDashedLine is used to draw a dashed line between two endpoints (x1,y1 and x2, y2).>KThe line is drawn using the color index specified. The portions of the lineNEthat are not drawn are left transparent so the background is visible.o

r... inside a function ...e(gdImagePtr im;
int black;
int white;:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	mA/* Allocate the color white (red, green and blue all maximum). */mUwhite = gdImageColorAllocate(im, 255, 255, 255);	fN/* Draw a dashed line from the upper left corner to the lower right corner. */$gdImageDashedLine(im, 0, 0, 99, 99);E/* ... Do something with the image, such as saving it to a file... */r/* Destroy it */1gdImageDestroy(im);=
r
void gdImagePolygon(gdImagePtr im, gdPointPtr points, int pointsTotal, int color)(FUNCTION) 
;gdImagePolygon is used to draw a polygon with the verticiese9(at least 3) specified, using the color index specified. >BSee also gdImageFilledPolygon.
E... inside a function ...O(gdImagePtr im;
int black;
int white;/* Points of polygon */e)gdPoint points[3];e:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	mA/* Allocate the color white (red, green and blue all maximum). */aUwhite = gdImageColorAllocate(im, 255, 255, 255);	c/* Draw a triangle. */points[0].x = 50;mpoints[0].y = 0;points[1].x = 99;mpoints[1].y = 99;epoints[2].x = 0;points[2].y = 99;r%gdImagePolygon(im, points, 3, white); E/* ... Do something with the image, such as saving it to a file... */*/* Destroy it */1gdImageDestroy(im);
r
void gdImageRectangle(gdImagePtr im, int x1, int y1, int x2, int y2, int color)(FUNCTION) 
AgdImageRectangle is used to draw a rectangle with the two cornersr9(upper left first, then lower right) specified, using theocolor index specified. f
x... inside a function ...n(gdImagePtr im;
int black;
int white;:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	yA/* Allocate the color white (red, green and blue all maximum). */Uwhite = gdImageColorAllocate(im, 255, 255, 255);	N2/* Draw a rectangle occupying the central area. */,gdImageRectangle(im, 25, 25, 74, 74, white);E/* ... Do something with the image, such as saving it to a file... */o/* Destroy it */1gdImageDestroy(im);,
~
void gdImageFilledPolygon(gdImagePtr im, gdPointPtr points, int pointsTotal, int color)(FUNCTION) 
AgdImageFilledPolygon is used to fill a polygon with the verticiest9(at least 3) specified, using the color index specified. <<See also gdImagePolygon.
C... inside a function ...l(gdImagePtr im;
int black;
int white;int red;/* Points of polygon */>)gdPoint points[3];D:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	A/* Allocate the color white (red, green and blue all maximum). */aUwhite = gdImageColorAllocate(im, 255, 255, 255);	e/* Allocate the color red. */ Ored = gdImageColorAllocate(im, 255, 0, 0);	c/* Draw a triangle. */points[0].x = 50;Apoints[0].y = 0;points[1].x = 99;.points[1].y = 99;epoints[2].x = 0;points[2].y = 99; /* Paint it in white */*+gdImageFilledPolygon(im, points, 3, white);i,/* Outline it in red; must be done second */AgdImagePolygon(im, points, 3, red);oE/* ... Do something with the image, such as saving it to a file... */a/* Destroy it */1gdImageDestroy(im);t
~
void gdImageFilledRectangle(gdImagePtr im, int x1, int y1, int x2, int y2, int color)(FUNCTION) 
MgdImageFilledRectangle is used to draw a solid rectangle with the two cornersr9(upper left first, then lower right) specified, using the*color index specified. m
r... inside a function ...a(gdImagePtr im;
int black;
int white;:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	tA/* Allocate the color white (red, green and blue all maximum). */gYwhite = int gdImageColorAllocate(im, 255, 255, 255);	t9/* Draw a filled rectangle occupying the central area. */>2gdImageFilledRectangle(im, 25, 25, 74, 74, white);E/* ... Do something with the image, such as saving it to a file... */e/* Destroy it */1gdImageDestroy(im);D
r
void gdImageArc(gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color) (FUNCTION) s
IgdImageArc is used to draw a partial ellipse centered at the given point,#@with the specified width and height in pixels. The arc begins at?the position in degrees specified by s and ends atg=the position specified by e. The arc is drawn in/?the color specified by the last argument. A circle can be drawn>;by beginning from 0 degrees and ending at 360 degrees, with Gwidth and height being equal. e must be greater than s. Values greater l$than 360 are interpreted modulo 360.
a... inside a function ...(gdImagePtr im;
int black;
int white;9im = gdImageCreate(100, 50);/(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	 A/* Allocate the color white (red, green and blue all maximum). */OUwhite = gdImageColorAllocate(im, 255, 255, 255);	.'/* Inscribe an ellipse in the image. */ .gdImageArc(im, 50, 25, 98, 48, 0, 360, white);E/* ... Do something with the image, such as saving it to a file... */r/* Destroy it */1gdImageDestroy(im);d
n
void gdImageFillToBorder(gdImagePtr im, int x, int y, int border, int color) (FUNCTION) i
DgdImageFillToBorder floods a portion of the image with the specifiedEcolor, beginning at the specified point and stopping at #Athe specified border color. For a way of flooding anA4area defined by the color of the starting point, see'gdImageFill.l

e3The border color cannot be a special colorD;such as gdTiled; it must be a propere,solid color. The fill color can be, however.

.>Note that gdImageFillToBorder is recursive. It is not the most8naive implementation possible, and the implementation is8expected to improve, but there will always be degenerate:cases in which the stack can become very deep. This can be;a problem in MSDOS and MS Windows environments. (Of course,d8in a Unix or NT environment with a proper stack, this isnot a problem at all.)

 ... inside a function ...a(gdImagePtr im;
int black;
int white;int red;9im = gdImageCreate(100, 50);e(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	eA/* Allocate the color white (red, green and blue all maximum). */NUwhite = gdImageColorAllocate(im, 255, 255, 255);	n/* Allocate the color red. */#Ored = gdImageColorAllocate(im, 255, 0, 0);	a'/* Inscribe an ellipse in the image. */g.gdImageArc(im, 50, 25, 98, 48, 0, 360, white);>/* Flood-fill the ellipse. Fill color is red, border color is 	white (ellipse). */,gdImageFillToBorder(im, 50, 50, white, red);E/* ... Do something with the image, such as saving it to a file... */,/* Destroy it */1gdImageDestroy(im);t
R
void gdImageFill(gdImagePtr im, int x, int y, int color) (FUNCTION) o
<gdImageFill floods a portion of the image with the specifiedEcolor, beginning at the specified point and flooding theg;surrounding region of the same color as the starting point.o;For a way of flooding a region defined by a specific border ,color rather than by its interior color, see7gdImageFillToBorder.

l?The fill color can be gdTiled, resultingE8in a tile fill using another image as the tile. However,;the tile image cannot be transparent. If the image you wish*0to fill with has a transparent color index, call;gdImageTransparent on theB5tile image and set the transparent color index to -1 #to turn off its transparency.l

o6Note that gdImageFill is recursive. It is not the most8naive implementation possible, and the implementation is8expected to improve, but there will always be degenerate:cases in which the stack can become very deep. This can be;a problem in MSDOS and MS Windows environments. (Of course,.8in a Unix or NT environment with a proper stack, this isnot a problem at all.)

i... inside a function ...g(gdImagePtr im;
int black;
int white;int red;9im = gdImageCreate(100, 50); (/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	RA/* Allocate the color white (red, green and blue all maximum). */lUwhite = gdImageColorAllocate(im, 255, 255, 255);	./* Allocate the color red. */EOred = gdImageColorAllocate(im, 255, 0, 0);	e'/* Inscribe an ellipse in the image. */B.gdImageArc(im, 50, 25, 98, 48, 0, 360, white);B/* Flood-fill the ellipse. Fill color is red, and will replace the"	black interior of the ellipse. */gdImageFill(im, 50, 50, red);*E/* ... Do something with the image, such as saving it to a file... */,/* Destroy it */1gdImageDestroy(im);/
W
void gdImageSetBrush(gdImagePtr im, gdImagePtr brush)g(FUNCTION) 
NA "brush" is an image used to draw wide, shaped strokes in another image. Just@as a paintbrush is not a single point, a brush image need not beDa single pixel. Any gd image can be used as a brush, and by;setting the transparent color index of the brush image witht?gdImageColorTransparent,p@a brush of any shape can be created. All line-drawing functions,2such as gdImageLine and:gdImagePolygon, will use the:current brush if the special "color" ?gdBrushed or gdStyledBrushed(is used when calling them.

f<gdImageSetBrush is used to specify the brush to be used in a8particular image. You can set any image to be the brush.:If the brush image does not have the same color map as the4first image, any colors missing from the first image9will be allocated. If not enough colors can be allocated, 7the closest colors already available will be used. This>9allows arbitrary GIFs to be used as brush images. It also0:means, however, that you should not set a brush unless you6will actually use it; if you set a rapid succession of<different brush images, you can quickly fill your color map,$and the results will not be optimal.

H:You need not take any special action when you are finished5with a brush. As for any other image, if you will noti1be using the brush image for any further purpose,m=you should call gdImageDestroy.a=You must not use the color gdBrushedn3if the current brush has been destroyed; you can of>%course set a new brush to replace it.e

g... inside a function ...r/gdImagePtr im, brush;,	FILE *in; 
int black;:im = gdImageCreate(100, 100);8/* Open the brush GIF. For best results, portions of the6	brush that should be transparent (ie, not part of the9	brush shape) should have the transparent color index. */ain = fopen("star.gif", "rb");#Ebrush = gdImageCreateFromGif(in);c(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	egdImageSetBrush(im, brush);*C/* Draw a line from the upper left corner to the lower right cornere	using the brush. */]gdImageLine(im, 0, 0, 99, 99, gdBrushed);sE/* ... Do something with the image, such as saving it to a file... *//* Destroy it */1gdImageDestroy(im);y/* Destroy the brush image */n4gdImageDestroy(brush);
T
void gdImageSetTile(gdImagePtr im, gdImagePtr tile)(FUNCTION) 
CA "tile" is an image used to fill an area with a repeated pattern.s3Any gd image can be used as a tile, and byr:setting the transparent color index of the tile image with?gdImageColorTransparent,6@a tile that allows certain parts of the underlying area to shine5through can be created. All region-filling functions,l2such as gdImageFill andFgdImageFilledPolygon, will use the7current tile if the special "color" n&gdTiled is used when calling them.

=:gdImageSetTile is used to specify the tile to be used in a7particular image. You can set any image to be the tile.l9If the tile image does not have the same color map as them4first image, any colors missing from the first image9will be allocated. If not enough colors can be allocated,47the closest colors already available will be used. Thisu8allows arbitrary GIFs to be used as tile images. It also9means, however, that you should not set a tile unless youA6will actually use it; if you set a rapid succession of;different tile images, you can quickly fill your color map,U$and the results will not be optimal.

e:You need not take any special action when you are finished4with a tile. As for any other image, if you will not0be using the tile image for any further purpose,=you should call gdImageDestroy.a;You must not use the color gdTiledP2if the current tile has been destroyed; you can of$course set a new tile to replace it.

 ... inside a function ... .gdImagePtr im, tile;	FILE *in;m
int black;:im = gdImageCreate(100, 100);7/* Open the tile GIF. For best results, portions of theb2	tile that should be transparent (ie, allowing the:	background to shine through) should have the transparent 	color index. */in = fopen("star.gif", "rb");aDtile = gdImageCreateFromGif(in);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	=gdImageSetTile(im, tile);d"/* Fill an area using the tile. */qgdImageFilledRectangle(im, 25, 25, 75, 75, gdTiled);E/* ... Do something with the image, such as saving it to a file... */t/* Destroy it */1gdImageDestroy(im); /* Destroy the tile image */3gdImageDestroy(tile);>
b
void gdImageSetStyle(gdImagePtr im, int *style, int styleLength)(FUNCTION) 
CIt is often desirable to draw dashed lines, dotted lines, and other)?variations on a broken line. gdImageSetStyle can be used to sete<any desired series of colors, including a special color that?leaves the background intact, to be repeated during the drawing of a line. A

=>To use gdImageSetStyle, create an array of integers and assign8them the desired series of color values to be repeated. @You can assign the special color value <gdTransparent to indicate that the existing color should>be left unchanged for that particular pixel (allowing a dashed7line to be attractively drawn over an existing image). o

h4Then, to draw a line using the style, use the normal8gdImageLine function with the5special color value gdStyled.n

l;As of version 1.1.1, the stylea7array is copied when you set the style, so you need not 8be concerned with keeping the array around indefinitely.7This should not break existing code that assumes stylesaare not copied.a

c9You can also combine styles and brushes to draw the brusho6image at intervals instead of in a continuous stroke. /When creating a style for use with a brush, theo<style values are interpreted differently: zero (0) indicates=pixels at which the brush should not be drawn, while one (1) 5indicates pixels at which the brush should be drawn. e0To draw a styled, brushed line, you must use the/special color value n3gdStyledBrushed. For an example of this featurer4in use, see gddemo.c (provided in the distribution).

I(gdImagePtr im;#int styleDotted[2], styleDashed[6]; 	FILE *in; 
int black;int red;:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	>Ored = gdImageColorAllocate(im, 255, 0, 0);	l9/* Set up dotted style. Leave every other pixel alone. */IstyleDotted[0] = red;hstyleDotted[1] = gdTransparent;2//* Set up dashed style. Three on, three off. */istyleDashed[0] = red; styleDashed[1] = red;bstyleDashed[2] = red;lstyleDashed[3] = gdTransparent; styleDashed[4] = gdTransparent;tstyleDashed[5] = gdTransparent;fE/* Set dotted style. Note that we have to specify how many pixels are/	in the style! */D$gdImageSetStyle(im, styleDotted, 2);G/* Draw a line from the upper left corner to the lower right corner. */O[gdImageLine(im, 0, 0, 99, 99, gdStyled);s/* Now the dashed line. */$gdImageSetStyle(im, styleDashed, 6);[gdImageLine(im, 0, 99, 0, 99, gdStyled);oF/* ... Do something with the image, such as saving it to a file ... *//* Destroy it */1gdImageDestroy(im);n

i,

Query Functions



-int gdImageBlue(gdImagePtr im, int color)r(MACRO) <
:gdImageBlue is a macro which returns the blue component ofCthe specified color index. Use this macro rather than accessing thesstructure members directly.hR
int gdImageGetPixel(gdImagePtr im, int x, int y)(FUNCTION) 
;gdImageGetPixel() retrieves the color index of a particulart0pixel. Always use this function to query pixels;Ido not access the pixels of the gdImage structure directly.t
F... inside a function ...s	FILE *in;gdImagePtr im;int c;in = fopen("mygif.gif", "rb");Bim = gdImageCreateFromGif(in);fclose(in);s>c = gdImageGetPixel(im, gdImageSX(im) / 2, gdImageSY(im) / 2);Hprintf("The value of the center pixel is %d; RGB values are %d,%d,%d\n",+	c, im->red[c], im->green[c], im->blue[c]);f1gdImageDestroy(im);r
o
6int gdImageBoundsSafe(gdImagePtr im, int x, int y)(FUNCTION) 
NgdImageBoundsSafe returns true (1) if the specified point is within the boundsHof the image, false (0) if not. This function is intended primarily for Duse by those who wish to add functions to gd. All of the gd drawing 8functions already clip safely to the edges of the image.
 ... inside a function ...i(gdImagePtr im;
int black;
int white;:im = gdImageCreate(100, 100);$if (gdImageBoundsSafe(im, 50, 50)) {/	printf("50, 50 is within the image bounds\n");F} else {0	printf("50, 50 is outside the image bounds\n");}c1gdImageDestroy(im);o

r.int gdImageGreen(gdImagePtr im, int color)(MACRO) g
<gdImageGreen is a macro which returns the green component ofCthe specified color index. Use this macro rather than accessing theDstructure members directly.u
.,int gdImageRed(gdImagePtr im, int color)(MACRO) y
8gdImageRed is a macro which returns the red component ofCthe specified color index. Use this macro rather than accessing themstructure members directly.m
int gdImageSX(gdImagePtr im)(MACRO) 
9gdImageSX is a macro which returns the width of the imageu3in pixels. Use this macro rather than accessing the structure members directly.
int gdImageSY(gdImagePtr im)(MACRO) r
:gdImageSY is a macro which returns the height of the image3in pixels. Use this macro rather than accessing thedstructure members directly.d
E>

Fonts and text-handling functions



>void gdImageChar(gdImagePtr im, gdFontPtr font, int x, int y,  int c, int color)(FUNCTION) 
;gdImageChar is used to draw single characters on the image.e;(To draw multiple characters, use m0gdImageString or .gdImageString16.) The second argument is a6pointer to a font definition structure; five fonts are<provided with gd, gdFontTiny, gdFontSmall, gdFontMediumBold,&gdFontLarge, and gdFontGiant. You must9include the files "gdfontt.h", "gdfonts.h", "gdfontmb.h",f("gdfontl.h" and "gdfontg.h" respectivelyBand (if you are not using a library-based approach) link with the 1corresponding .c files to use the provided fonts.p$The character specified by the fifth6argument is drawn from left to right in the specified @color. (See gdImageCharUp for a way%of drawing vertical text.) Pixels not>;set by a particular character retain their previous color. A
t#include "gd.h"a#include "gdfontl.h"... inside a function ...l(gdImagePtr im;
int black;
int white;:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	 A/* Allocate the color white (red, green and blue all maximum). */tUwhite = gdImageColorAllocate(im, 255, 255, 255);	/* Draw a character. */r/gdImageChar(im, gdFontLarge, 0, 0, 'Q', white);cE/* ... Do something with the image, such as saving it to a file... */a/* Destroy it */1gdImageDestroy(im);)

@void gdImageCharUp(gdImagePtr im, gdFontPtr font, int x, int y, int c, int color)F(FUNCTION) 
=gdImageCharUp is used to draw single characters on the image,rotated 90 degrees.H=(To draw multiple characters, use t4gdImageStringUp or 0gdImageStringUp16.) The second argument is a6pointer to a font definition structure; five fonts are<provided with gd, gdFontTiny, gdFontSmall, gdFontMediumBold,&gdFontLarge, and gdFontGiant. You must9include the files "gdfontt.h", "gdfonts.h", "gdfontmb.h",S("gdfontl.h" and "gdfontg.h" respectivelyBand (if you are not using a library-based approach) link with the Mcorresponding .c files to use the provided fonts. The character specified by ethe fifth argument is drawn Dfrom bottom to top, rotated at a 90-degree angle, in the specified =color. (See gdImageChar for a waya(of drawing horizontal text.) Pixels not;set by a particular character retain their previous color. u
e#include "gd.h"h#include "gdfontl.h"... inside a function ...g(gdImagePtr im;
int black;
int white;:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	lA/* Allocate the color white (red, green and blue all maximum). */nUwhite = gdImageColorAllocate(im, 255, 255, 255);	 H/* Draw a character upwards so it rests against the top of the image. */gdImageCharUp(im, gdFontLarge, m 	0, gdFontLarge->h, 'Q', white);E/* ... Do something with the image, such as saving it to a file... */t/* Destroy it */1gdImageDestroy(im); 

@void gdImageString(gdImagePtr im, gdFontPtr font, int x, int y, unsigned char *s, int color)(FUNCTION) 
?gdImageString is used to draw multiple characters on the image.x7(To draw single characters, use *gdImageChar.) The second argument is a6pointer to a font definition structure; five fonts are<provided with gd, gdFontTiny, gdFontSmall, gdFontMediumBold,&gdFontLarge, and gdFontGiant. You must9include the files "gdfontt.h", "gdfonts.h", "gdfontmb.h",#("gdfontl.h" and "gdfontg.h" respectivelyBand (if you are not using a library-based approach) link with the 1corresponding .c files to use the provided fonts.d&The null-terminated C string specifiedCby the fifth argument is drawn from left to right in the specified uEcolor. (See gdImageStringUp for a wayD&of drawing vertical text.) Pixels not;set by a particular character retain their previous color. a
#include "gd.h"g#include "gdfontl.h"#include <string.h> ... inside a function ...x(gdImagePtr im;
int black;
int white;/* String to draw. */hchar *s = "Hello.";o:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	,A/* Allocate the color white (red, green and blue all maximum). */RUwhite = gdImageColorAllocate(im, 255, 255, 255);	 /* Draw a centered string. */igdImageString(im, gdFontLarge,.	im->w / 2 - (strlen(s) * gdFontLarge->w / 2), 	im->h / 2 - gdFontLarge->h / 2,	s, white);DE/* ... Do something with the image, such as saving it to a file... */r/* Destroy it */1gdImageDestroy(im);r

Bvoid gdImageString16(gdImagePtr im, gdFontPtr font, int x, int y, !unsigned short *s, int color)a(FUNCTION) 
FgdImageString is used to draw multiple 16-bit characters on the image.7(To draw single characters, use i*gdImageChar.) The second argument is a6pointer to a font definition structure; five fonts are<provided with gd, gdFontTiny, gdFontSmall, gdFontMediumBold,&gdFontLarge, and gdFontGiant. You must9include the files "gdfontt.h", "gdfonts.h", "gdfontmb.h",e("gdfontl.h" and "gdfontg.h" respectivelyBand (if you are not using a library-based approach) link with the 1corresponding .c files to use the provided fonts. HThe null-terminated string of characters represented as 16-bit unsigned Kshort integers specified by the fifth argument is drawn from left to right Nin the specified aIcolor. (See gdImageStringUp16 for a wayT&of drawing vertical text.) Pixels not;set by a particular character retain their previous color. 

e@This function was added in gd1.3 to provide a means of rendering>fonts with more than 256 characters for those who have them. AKmore frequently used routine is gdImageString. 

Bvoid gdImageStringUp(gdImagePtr im, gdFontPtr font, int x, int y, unsigned char *s, int color)(FUNCTION) 
AgdImageStringUp is used to draw multiple characters on the image,rotated 90 degrees.,9(To draw single characters, use D,gdImageCharUp.) The second argument is a6pointer to a font definition structure; five fonts are<provided with gd, gdFontTiny, gdFontSmall, gdFontMediumBold,&gdFontLarge, and gdFontGiant. You must9include the files "gdfontt.h", "gdfonts.h", "gdfontmb.h",r("gdfontl.h" and "gdfontg.h" respectivelyBand (if you are not using a library-based approach) link with the Wcorresponding .c files to use the provided fonts.The null-terminated C string specified :by the fifth argument is drawn from bottom to top (rotated*90 degrees) in the specified color. (See 4gdImageString for a way(of drawing horizontal text.) Pixels not;set by a particular character retain their previous color. h
u#include "gd.h"t#include "gdfontl.h"#include <string.h>e... inside a function ...M(gdImagePtr im;
int black;
int white;/* String to draw. */gchar *s = "Hello.";r:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	HA/* Allocate the color white (red, green and blue all maximum). */mUwhite = gdImageColorAllocate(im, 255, 255, 255);	;/* Draw a centered string going upwards. Axes are reversed,a4	and Y axis is decreasing as the string is drawn. */ gdImageStringUp(im, gdFontLarge, 	im->w / 2 - gdFontLarge->h / 2,.	im->h / 2 + (strlen(s) * gdFontLarge->w / 2),	s, white); E/* ... Do something with the image, such as saving it to a file... */o/* Destroy it */1gdImageDestroy(im);n
Dvoid gdImageStringUp16(gdImagePtr im, gdFontPtr font, int x, int y, !unsigned short *s, int color)a(FUNCTION) 
GgdImageString is used to draw multiple 16-bit characters vertically on Bthe image. (To draw single characters, use *gdImageChar.) The second argument is a6pointer to a font definition structure; five fonts are<provided with gd, gdFontTiny, gdFontSmall, gdFontMediumBold,&gdFontLarge, and gdFontGiant. You must9include the files "gdfontt.h", "gdfonts.h", "gdfontmb.h",P("gdfontl.h" and "gdfontg.h" respectivelyBand (if you are not using a library-based approach) link with the 1corresponding .c files to use the provided fonts.gHThe null-terminated string of characters represented as 16-bit unsigned Jshort integers specified by the fifth argument is drawn from bottom to topin the specified color. rA(See gdImageStringUp16 for a wayg(of drawing horizontal text.) Pixels not;set by a particular character retain their previous color. f

.@This function was added in gd1.3 to provide a means of rendering>fonts with more than 256 characters for those who have them. ATmore frequently used routine is gdImageStringUp.

6

Color-handling functions


#
d@int gdImageColorAllocate(gdImagePtr im, int r, int g, int b)(FUNCTION) 
=gdImageColorAllocate finds the first available color index ing;the image specified, sets its RGB values to those requesteds(255 is the maximum for each),8and returns the index of the new color table entry. When>creating a new image, the first time you invoke this function,4you are setting the background color for that image.

CIn the event that all gdMaxColors colorss<(256) have already been allocated, gdImageColorAllocate will9return -1 to indicate failure. (This is not uncommon whenp=working with existing GIF files that already use 256 colors.)eNote that gdImageColorAllocate;does not check for existing colors that match your request;6see gdImageColorExact:and gdImageColorClosest7for ways to locate existing colors that approximate the>?color desired in situations where a new color is not available.g

<... inside a function ...n(gdImagePtr im;
int black;int red;:im = gdImageCreate(100, 100);(/* Background color (first allocated) */Oblack = gdImageColorAllocate(im, 0, 0, 0);	,/* Allocate the color red. */hOred = gdImageColorAllocate(im, 255, 0, 0);	dN/* Draw a dashed line from the upper left corner to the lower right corner. */)gdImageDashedLine(im, 0, 0, 99, 99, red);DE/* ... Do something with the image, such as saving it to a file... */>/* Destroy it */1gdImageDestroy(im);o
"
?int gdImageColorClosest(gdImagePtr im, int r, int g, int b)n(FUNCTION) 
7gdImageColorClosest searches the colors which have been=7defined thus far in the image specified and returns thes:index of the color with RGB values closest to those of the8request. (Closeness is determined by Euclidian distance,Cwhich is used to determine the distance in three-dimensional color tspace between colors.)

"2If no colors have yet been allocated in the image,gdImageColorClosest returns -1.e

r<This function is most useful as a backup method for choosing.a drawing color when an image already contains7gdMaxColors (256) colors andt4no more can be allocated. (This is not uncommon when>working with existing GIF files that already use many colors.)6See gdImageColorExact,for a method of locating exact matches only.

d... inside a function ...n(gdImagePtr im;	FILE *in;gint red;</* Let's suppose that photo.gif is a scanned photograph with	many colors. */in = fopen("photo.gif", "rb");Bim = gdImageCreateFromGif(in);fclose(in); "/* Try to allocate red directly */Ored = gdImageColorAllocate(im, 255, 0, 0);	n#/* If we fail to allocate red... */Hif (red == (-1)) {/	/* Find the closest color instead. */5*	red = gdImageColorClosest(im, 255, 0, 0);}rM/* Draw a dashed line from the upper left corner to the lower right corner */2)gdImageDashedLine(im, 0, 0, 99, 99, red);.E/* ... Do something with the image, such as saving it to a file... */s/* Destroy it */1gdImageDestroy(im);>
=int gdImageColorExact(gdImagePtr im, int r, int g, int b)i(FUNCTION) 
5gdImageColorExact searches the colors which have beeno7defined thus far in the image specified and returns thes6index of the first color with RGB values which exactly=match those of the request. If no allocated color matches then0request precisely, gdImageColorExact returns -1.:See gdImageColorClosest;for a way to find the color closest to the color requested."
n... inside a function ...g(gdImagePtr im;int red;in = fopen("photo.gif", "rb");Bim = gdImageCreateFromGif(in);fclose(in);tC/* The image may already contain red; if it does, we'll save a slote+	in the color table by using that color. */f"/* Try to allocate red directly */'red = gdImageColorExact(im, 255, 0, 0);d%/* If red isn't already present... */iif (red == (-1)) {0	/* Second best: try to allocate it directly. */P	red = gdImageColorAllocate(im, 255, 0, 0);	A	/* Out of colors, so find the closest color instead. */e*	red = gdImageColorClosest(im, 255, 0, 0);}eM/* Draw a dashed line from the upper left corner to the lower right corner */I)gdImageDashedLine(im, 0, 0, 99, 99, red); E/* ... Do something with the image, such as saving it to a file... */T/* Destroy it */1gdImageDestroy(im);t
!
s)int gdImageColorsTotal(gdImagePtr im)U(MACRO) h
9gdImageColorsTotal is a macro which returns the number ofi7colors currently allocated in the image. Use this macrog7to obtain this information; do not access the structure directly. 
-int gdImageColorRed(gdImagePtr im, int c)p(MACRO) o
8gdImageColorRed is a macro which returns the red portion3of the specified color in the image. Use this macrod7to obtain this information; do not access the structure directly.o
/int gdImageColorGreen(gdImagePtr im, int c)I(MACRO) f
<gdImageColorGreen is a macro which returns the green portion3of the specified color in the image. Use this macrod7to obtain this information; do not access the structure. directly.f
r.int gdImageColorBlue(gdImagePtr im, int c)(MACRO) *
;gdImageColorBlue is a macro which returns the green portion,3of the specified color in the image. Use this macroc7to obtain this information; do not access the structure/ directly.,#
r+int gdImageGetInterlaced(gdImagePtr im) (MACRO) a
6gdImageGetInterlaced is a macro which returns true (1)-if the image is interlaced, false (0) if not.d2Use this macro to obtain this information; do not access the structure directly.7See gdImageInterlace forta means of interlacing images.$
,int gdImageGetTransparent(gdImagePtr im)(MACRO) =
3gdImageGetTransparent is a macro which returns the N-current transparent color index in the image.67If there is no transparent color, gdImageGetTransparents>returns -1. Use this macro to obtain this information; do not access the structure directly.%
9void gdImageColorDeallocate(gdImagePtr im, int color)e(FUNCTION) 
9gdImageColorDeallocate marks the specified color as beinge=available for reuse. It does not attempt to determine whetherd:the color index is still in use in the image. After a call#to this function, the next call to f8gdImageColorAllocate3for the same image will set new RGB values for thatw4color index, changing the color of any pixels which 1have that index as a result. If multiple calls topBgdImageColorDeallocate are made consecutively, the lowest-numbered,index among them will be reused by the next ? gdImageColorAllocate call.n
A... inside a function ...r(gdImagePtr im;int red, blue;in = fopen("photo.gif", "rb");Bim = gdImageCreateFromGif(in);fclose(in);h&/* Look for red in the color table. */'red = gdImageColorExact(im, 255, 0, 0);e/* If red is present... */if (red != (-1)) {	/* Deallocate it. */c!	gdImageColorDeallocate(im, red);<)	/* Allocate blue, reusing slot in table.t+		Existing red pixels will change color. */ ,	blue = gdImageColorAllocate(im, 0, 0, 255);} E/* ... Do something with the image, such as saving it to a file... */i/* Destroy it */1gdImageDestroy(im);5
&
:void gdImageColorTransparent(gdImagePtr im, int color)(FUNCTION) 
8gdImageColorTransparent sets the transparent color index;for the specified image to the specified index. To indicateo:that there should be no transparent color, invoke1gdImageColorTransparent with a color index of -1.h

'The color index used should be an index Fallocated by gdImageColorAllocate,5whether explicitly invoked by your code or implicitlyqinvoked by loading an image.>In order to ensure that your image has a reasonable appearance;when viewed by users who do not have transparent backgroundo:capabilities, be sure to give reasonable RGB values to the2color you allocate for use as a transparent color,1even though it will be transparent on systems>that support transparency.<

"... inside a function ...t(gdImagePtr im;
int black;FILE *in, *out;Hin = fopen("photo.gif", "rb");Bim = gdImageCreateFromGif(in);fclose(in);E@/* Look for black in the color table and make it transparent. */Hblack = gdImageColorExact(im, 0, 0, 0);/* If black is present... */if (black != (-1)) {	/* Make it transparent */$	gdImageColorTransparent(im, black);} 7/* Save the newly-transparent image back to the file */sout = fopen("photo.gif", "wb");M.gdImageGif(im, out);fclose(out);/* Destroy it */1gdImageDestroy(im);m

=

Copying and resizing functions

m
void gdImageCopy(gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h) (FUNCTION) d
AgdImageCopy is used to copy a rectangular portion of one image to)>another image. (For a way of stretching or shrinking the image2in the process, see gdImageCopyResized.)

CThe dst argument is the destination image to which the=Bregion will be copied. The src argument is the source<image from which the region is copied. The dstXDand dstY arguments specify the point in the destination?image to which the region will be copied. The srcXl=and srcY arguments specify the upper left cornerd5of the region in the source image. The we9and h arguments specify the width and height of the region.

.?When you copy a region from one location in an image to anotherr@location in the same image, gdImageCopy will perform as expected7unless the regions overlap, in which case the result iseunpredictable.

nAImportant note on copying between images: since ddifferent images do Lnot necessarily have the same color tables, pixels are not simply set to the>same color index values to copy them. gdImageCopy will attempt;to find an identical RGB value in the destination image foro7each pixel in the copied portion of the source image bys?invoking gdImageColorExact. Ifi6such a value is not found, gdImageCopy will attempt to@allocate colors as needed using 8gdImageColorAllocate. If both of these methods fail,7gdImageCopy will invoke c<gdImageColorClosest to find the color in the destination6image which most closely approximates the color of thepixel being copied.h

u... Inside a function ...E+gdImagePtr im_in;l,gdImagePtr im_out;	int x, y;o	FILE *in;o
FILE *out;2/* Load a small gif to tile the larger one with */in = fopen("small.gif", "rb");Eim_in = gdImageCreateFromGif(in);rfclose(in);g</* Make the output image four times as large on both axes */Sim_out = gdImageCreate(im_in->sx * 4, im_in->sy * 4);  5/* Now tile the larger image using the smaller one */dfor (y = 0; (y < 4); y++) {)	for (x = 0; (x < 4); x++) {		gdImageCopy(im_out, im_in, { 			x * im_in->sx, y * im_in->sy,			0, 0,			im_in->sx, im_in->sy);I	}}oout = fopen("tiled.gif", "wb");A2gdImageGif(im_out, out);fclose(out);4gdImageDestroy(im_in);5gdImageDestroy(im_out);f
ª
void gdImageCopyResized(gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int destW, int destH, int srcW, int srcH) (FUNCTION) r
HgdImageCopyResized is used to copy a rectangular portion of one image toDanother image. The X and Y dimensions of the original region and theDdestination region can vary, resulting in stretching or shrinking ofBthe region as appropriate. (For a simpler version of this function>which does not deal with resizing, see gdImageCopy.)r

dCThe dst argument is the destination image to which thelBregion will be copied. The src argument is the source<image from which the region is copied. The dstXDand dstY arguments specify the point in the destination?image to which the region will be copied. The srcXM=and srcY arguments specify the upper left cornerr8of the region in the source image. The dstW<and dstH arguments specify the width and height0of the destination region. The srcW<and srcH arguments specify the width and height>of the source region and can differ from the destination size,:allowing a region to be scaled during the copying process.

U?When you copy a region from one location in an image to anotheru@location in the same image, gdImageCopy will perform as expected7unless the regions overlap, in which case the result isRAunpredictable. If this presents a problem, create a scratch image)&in which to keep intermediate results.

tHImportant note on copying between images: since images Ido not necessarily have the same color tables, pixels are not simply set eEto the same color index values to copy them. gdImageCopy will attemptd;to find an identical RGB value in the destination image forN7each pixel in the copied portion of the source image bys?invoking gdImageColorExact. Ifi6such a value is not found, gdImageCopy will attempt to@allocate colors as needed using 8gdImageColorAllocate. If both of these methods fail,7gdImageCopy will invoke <<gdImageColorClosest to find the color in the destination6image which most closely approximates the color of thepixel being copied.m

e... Inside a function ... +gdImagePtr im_in;a,gdImagePtr im_out;	int x, y;g	FILE *in;a
FILE *out;2/* Load a small gif to expand in the larger one */in = fopen("small.gif", "rb");Eim_in = gdImageCreateFromGif(in);Ifclose(in);l</* Make the output image four times as large on both axes */Sim_out = gdImageCreate(im_in->sx * 4, im_in->sy * 4); o7/* Now copy the smaller image, but four times larger */e.gdImageCopyResized(im_out, im_in, 0, 0, 0, 0, 	im_out->sx, im_out->sy,	im_in->sx, im_in->sy);	 rout = fopen("large.gif", "wb");e2gdImageGif(im_out, out);fclose(out);4gdImageDestroy(im_in);5gdImageDestroy(im_out);(

l3

Miscellaneous Functions

/
m
gdImageInterlace(gdImagePtr im, int interlace) (FUNCTION)i
GgdImageInterlace is used to determine whether an image should be storedfCin a linear fashion, in which lines will appear on the display fromy>first to last, or in an interlaced fashion, in which the image>will "fade in" over several passes. By default, images are not interlaced. 

>A nonzero value for the interlace argument turns on interlace;<a zero value turns it off. Note that interlace has no effect:on other functions, and has no meaning unless you save the:image in GIF format; the gd and xbm formats do not support interlace. e

dNWhen a GIF is loaded with gdImageCreateFromGifE, interlace will be set according to the setting in the GIF file.n

CNote that many GIF viewers and web browsers do not supporta?interlace. However, the interlaced GIF should still display; itb8will simply appear all at once, just as other images do.

ogdImagePtr im;
FILE *out;%/* ... Create or load the image... */t/* Now turn on interlace */ gdImageInterlace(im, 1); s/* And open an output file */iout = fopen("test.gif", "wb");/* And save the image */.gdImageGif(im, out);fclose(out);1gdImageDestroy(im);a

n*

Constants


A
gdBrushed (CONSTANT)c
5Used in place of a color when invoking a line-drawingt7function such as gdImageLine4or gdImageRectangle..When gdBrushed is used as the color, the brush=image set with gdImageSetBrushf9is drawn in place of each pixel of the line (the brush isd2usually larger than one pixel, creating the effectof a wide paintbrush). See also 8gdStyledBrushed for a wayBto draw broken lines with a series of distinct copies of an image.M
gdMaxColors(CONSTANT)>
DThe constant 256. This is the maximum number of colors in a GIF file@according to the GIF standard, and is also the maximum number ofcolors in a gd image.d?
gdStyled (CONSTANT)<
5Used in place of a color when invoking a line-drawingn7function such as gdImageLiner4or gdImageRectangle.@When gdStyled is used as the color, the colors of the pixels are/drawn successively from the style that has been 8set with gdImageSetStyle.$If the color of a pixel is equal to 6gdTransparent, that pixel7is not altered. (This mechanism is completely unrelated 3to the "transparent color" of the image itself; seen>gdImageColorTransparent6gdImageColorTransparent for that mechanism.) See also 0 gdStyledBrushed.M
gdStyledBrushed (CONSTANT)
5Used in place of a color when invoking a line-drawingl7function such as gdImageLinel4or gdImageRectangle.4When gdStyledBrushed is used as the color, the brush=image set with gdImageSetBrushg6is drawn at each pixel of the line, providing that the=style set with gdImageSetStylea1contains a nonzero value (OR gdTransparent, whicho6does not equal zero but is supported for consistency) Kfor the current pixel. (Pixels are drawn successively from the style as thel2line is drawn, returning to the beginning when the7available pixels in the style are exhausted.) Note thatiCthis differs from the behavior of gdStyled,m3in which the values in the style are used as actual>'pixel colors, except for gdTransparent.*C
gdDashSize (CONSTANT)
:The length of a dash in a dashed line. Defined to be 4 for.backwards compatibility with programs that use6gdImageDashedLine. New.programs should use )gdImageSetStyle and call the standard;.gdImageLine function,with the special "color" >gdStyled or gdStyledBrushed.=
gdTiled (CONSTANT)I
EUsed in place of a normal color in /<gdImageFilledRectangle, gdImageFilledPolygon,HKgdImageFill, and a9gdImageFillToBorder. gdTiled selects a pixel from thea@tile image set with gdImageSetTile7in such a way as to ensure that the filled area will ber;tiled with copies of the tile image. See the discussions ofi*gdImageFill andBgdImageFillToBorder for special'restrictions regarding those functions.nI
gdTransparent (CONSTANT)h
9Used in place of a normal color in a style to be set withm0gdImageSetStyle. 5gdTransparent is not the transparente7color index of the image; for that functionality pleasegBsee gdImageColorTransparent.
oJ

About the additional .gd image file format

AIn addition to reading and writing the GIF format and reading theu<X Bitmap format, gd has the capability to read and write its:own ".gd" format. This format is not intended for:general purpose use and should never be used to distribute@images. It is not a compressed format. Its purpose is solely to =allow very fast loading of images your program needs often int?order to build other images for output. If you are experiencingo>performance problems when loading large, fixed GIF images your8program needs to produce its output images, you may wish8to examine the functions ?gdImageCreateFromGd and gdImageGd, 'which read and write .gd format images.h

eAThe program "giftogd.c" is provided as a simple way of convertinge=.gif files to .gd format. I emphasize again that you will nothEneed to use this format unless you have a need for high-speed loadinge0of a few frequently-used images in your program.<

Please tell us you're using gd!

5When you contact us and let us know you are using gd,s?you help us justify the time spent in maintaining and improvingi6it. So please let us know. If the results are publicly>visible on the web, a URL is a wonderful thing to receive, but>if it's not a publicly visible project, a simple note is just as welcome.l4

If you have problems

:If you have any difficulties with gd, feel free to contactJthe author, Thomas Boutell. ,Be sure to read this manual carefully first.5

Alphabetical quick index

g$gdBrushed |'gdDashSize | pgdFont | p%gdFontPtr | =!gdImage | t'gdImageArc | (gdImageBlue |5gdImageBoundsSafe | e)gdImageChar | *-gdImageCharUp | g;gdImageColorAllocate | u9gdImageColorClosest | (?gdImageColorDeallocate | ,5gdImageColorExact | DAgdImageColorTransparent | _)gdImageCopy | M7gdImageCopyResized | a-gdImageCreate | t9gdImageCreateFromGd | I;gdImageCreateFromGif | e;gdImageCreateFromXbm | s5gdImageDashedLine | /gdImageDestroy | a)gdImageFill | d9gdImageFillToBorder | o?gdImageFilledRectangle | n%gdImageGd | o:gdImageGetInterlaced |1gdImageGetPixel | h<gdImageGetTransparent |'gdImageGif | e*gdImageGreen |2gdImageInterlace |)gdImageLine | r:gdImageFilledPolygon |.gdImagePolygon |'gdImagePtr | C3gdImageRectangle | r&gdImageRed |0gdImageSetBrush |1gdImageSetPixel | m0gdImageSetStyle |.gdImageSetTile |-gdImageString | a1gdImageString16 | e1gdImageStringUp | l3gdImageStringUp16 | n(gdMaxColors | gdPoint |"gdStyled |0gdStyledBrushed | gdTiled |*gdTransparent

e&Boutell.Com, Inc.ew