Need more help? Have us do it!
Boutell.Com Consulting Services

gd 2.0.20

A graphics library for fast image creation

Follow this link to the latest version of this document.

UPGRADING UNIX USERS: READ THIS FIRST! Modern versions of gd install by default to /usr/local/lib and /usr/local/include. If you already have an older version of gd in /usr/lib and /usr/include, you may wish to use:
./configure --prefix=/usr
To ensure that your new installation overwrites the old.

ABOUT GD AND GIF: gd 2.0.20 creates PNG, JPEG and WBMP images, not GIF images. This is a good thing. PNG is a more compact format, and full compression is available. JPEG works best with photographic images, and is still more compatible with the major Web browsers than even PNG is. WBMP is intended for wireless devices (not regular web browsers). Old code will need modification to call gdImagePng or gdImageJpeg instead of gdImageGif. Please do not ask us to send you the old GIF version of GD. Yes, Unisys still holds a patent on the LZW compression algorithm in some countries. The best solution is to move to legally unencumbered, well-compressed, modern image formats such as PNG and JPEG as soon as possible.

When building from soruce, gd 2.0.20 requires that the following libraries also be installed, in order to produce the related image formats. The win32 binary release (bgd) already contains the appropriate libraries. You may skip libraries associated with formats you do not use:

libpng (see the libpng home page), if you want PNG

zlib (see the info-zip home page), if you want PNG

jpeg-6b or later, if desired (see the Independent JPEG Group home page), if you want JPEG

If you want to use the TrueType font support, you must also install the FreeType 2.x library, including the header files. See the Freetype Home Page, or SourceForge. No, I cannot explain why that site is down on a particular day, and no, I can't send you a copy.

If you want to use the Xpm color bitmap loading support, you must also have the X Window System and the Xpm library installed (Xpm is often included in modern X distributions). Most of the time you won't need Xpm.

Please read the documentation and install the required libraries. Do not send email asking why png.h is not found. Do not send email asking why libgd.so is not found, either. See the requirements section for more information. Thank you!

Table of Contents

Up to the Boutell.Com, Inc. Home Page

Credits and license terms

In order to resolve any possible confusion regarding the authorship of gd, the following copyright statement covers all of the authors who have required such a statement. If you are aware of any oversights in this copyright notice, please contact Thomas Boutell who will be pleased to correct them.

COPYRIGHT STATEMENT FOLLOWS THIS LINE
Portions copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002 by Cold Spring Harbor Laboratory. Funded under Grant P41-RR02188 by the National Institutes of Health.

Portions copyright 1996, 1997, 1998, 1999, 2000, 2001, 2002 by Boutell.Com, Inc.

Portions relating to GD2 format copyright 1999, 2000, 2001, 2002 Philip Warner.

Portions relating to PNG copyright 1999, 2000, 2001, 2002 Greg Roelofs.

Portions relating to gdttf.c copyright 1999, 2000, 2001, 2002 John Ellson (ellson@graphviz.org).

Portions relating to gdft.c copyright 2001, 2002 John Ellson (ellson@graphviz.org).

Portions relating to JPEG and to color quantization copyright 2000, 2001, 2002, Doug Becker and copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, Thomas G. Lane. This software is based in part on the work of the Independent JPEG Group. See the file README-JPEG.TXT for more information.

Portions relating to WBMP copyright 2000, 2001, 2002 Maurice Szmurlo and Johan Van den Brande.

Permission has been granted to copy, distribute and modify gd in any context without fee, including a commercial application, provided that this notice is present in user-accessible supporting documentation.

This does not affect your ownership of the derived work itself, and the intent is 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. Credit must be given in user-accessible documentation.

This software is provided "AS IS." The copyright holders disclaim all warranties, either express or implied, including but not limited to implied warranties of merchantability and fitness for a particular purpose, with respect to this code and accompanying documentation.

Although their code does not appear in gd 2.0.4, the authors wish to thank David Koblas, David Rowley, and Hutchison Avenue Software Corporation for their prior contributions.

END OF COPYRIGHT STATEMENT

What is gd?

gd is a graphics library. It allows your code to quickly draw images complete with lines, arcs, text, multiple colors, cut and paste from other images, and flood fills, and write out the result as a PNG or JPEG file. This is particularly useful in World Wide Web applications, where PNG and JPEG are two of the formats accepted for inline images by most browsers.

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 looking in the wrong place, unless you are installing a required library in order to run an application.

gd 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 2.0 does include most frequently requested features, including both truecolor and palette images, resampling (smooth resizing of truecolor images) and so forth.

What if I want to use another programming language?

Not all of these tools are necessarily up to date and fully compatible with 2.0.20.

PHP

A variant of gd 2.x is included in PHP 4.3.0. It is also possible to patch PHP 4.2.3 for use with gd 2.0.20; see the gd home page for a link to that information. It would be a Good Idea to merge all of the things that are better in mainstream gd and all of the things that are better in PHP gd at some point in the near future.

Perl

gd can also be used from Perl, courtesy of Lincoln Stein's GD.pm library, which uses gd as the basis for a set of Perl 5.x classes. Highly recommended.

OCaml

gd can be used from OCaml, thanks to Matt Gushee's GD4O project.

Tcl

gd can be used from Tcl with John Ellson's Gdtclft dynamically loaded extension package.

Pascal

Pascal enthusiasts should look into Michael Bradbury's gdfp package.

REXX

A gd interface for the REXX language is available.

Any Language

The "fly" interpreter performs gd operations specified in a text file. You can output the desired commands to a simple text file from whatever scripting language you prefer to use, then invoke the interpreter.

  • fly, by Martin Gleeson

What's new in version 2.0.20?

  • Version 2.0.20 restores the gdFreeFontCache function, an undocumented function added in an earlier release which now simply calls gdFontCacheShutdown for backwards compatibility. This repairs build problems when compiling PHP against the latest gd.

What's new in version 2.0.19?

  • Version 2.0.19 restored extern declarations for the gd font pointers inadvertently removed in 2.0.18.

What's new in version 2.0.18?

  • A Win32 binary distribution of "bgd.dll," built with mingw32 and tested with win32 versions of the demo programs as console applications, is now available.
  • Semicolon rather than space used as the default separator of alternative font file paths in gdImageStringFT, for better compatibility with Windows and other environments where spaces are common in paths.
  • The circletexttest demo no longer fails to compile when JPEG support happens to be absent.

What's new in version 2.0.17?

Minor compilation and packaging problems with 2.0.16 were corrected. If 2.0.16 compiled without errors for you, then you don't need to upgrade to 2.0.17.

What's new in version 2.0.16?

  • Thread safety for freetype text output. Background: all gd functions were already thread safe, as long as only one thread manipulates each image -- except for gdImageStringFT and gdImageStringFTEx. This is because of a shared freetype font cache. Sharing the cache between images is worthwhile, so "configure" now detects pthreads and uses it to wrap freetype text output in a critical section if available. There is also critical section support under WIN32. Those who wish to be strictly thread-safe should call the new function gdFontCacheSetup before allowing any thread to use freetype text calls. Otherwise this function is automatically invoked on the first use of freetype, with a very small but real chance of a race condition.
  • gdImageSquareToCircle performs a "polar coordinate transform," returning a new image in which the X axis of the original has been remapped to theta (angle) and the Y axis of the original has been remapped to rho (distance from center).
  • gdImageStringFTCircle wraps text in a circle around a specified center point. This function takes advantage of gdImageSquareToCircle. The result is very smooth, although it takes some time to compute. Thanks to Steve Bassi for sponsoring this work.
  • gdImageSharpen, contributed by Paul Troughton. Thank you.
  • Christophe Thomas corrected gdft.c to include freetype header files in the way that is now mandatory in freetype 2.1.6 and above.
  • Gustavo Scotti fixed a memory leak in gdft.c.
  • Clipping rectangle respected in freetype text output. Thanks to Matt McNabb.
  • Paul den Dulk found a degenerate case that crashes gdImageToPalette. Fixed.
  • Optimization by Ilia Chipitsine to avoid wasting time with offscreen scanlines during polygon rasterization.
  • Optimized PNG saving by Phong Tran. Speeds up saves a little bit.

What's new in version 2.0.15?

  • gd.c in 2.0.14 contained an instance of declaring variables after the first line of executable code appears. This is of course not allowed by ANSI C, although many compilers accept it. My apologies. Thanks to Jeff Vendetti for reporting this quickly.

What's new in version 2.0.14?

  • 2.0.13 was available for mere minutes due to a typo in the new bounds-checking code for antialiased line drawing. Fixed.
  • Not all platforms -- notably msys/mingw -- have an ssize_t type. We now call an int an int in gd_jpeg.c, with good results. (Note: ssize_t is signed, unlike size_t, and it needs to be here.)

What's new in version 2.0.13?

  • The main() function of one of the test programs was accidentally included in the gd shared library, causing problems on some platforms. This has been corrected. Thanks to many people who pointed this out.
  • The antialiased drawing functions now have proper bounds checking. Thanks to Arne Jorgensen.
  • A void function returned a value in gd_png.c, causing warnings and, on some platforms, compilation errors but no reported runtime problems. Thanks to Kevin Smith, among others.
  • Autohinting was being forced ON for freetype text output. This is apparently meant only for testing freetype and does not look as good as the default behavior (FT_LOAD_DEFAULT). Thanks to Bob Ostermann.
  • penf.x is properly reset when newlines are encountered in freetype text output. Thanks to Christopher J. Grayce.

What's new in version 2.0.12?

  • Small but numerous code cleanups by Dr. Martin Zinser.
  • gdImageSetClip and gdImageGetClip have been added. All drawing routines now stay within the specified clipping rectangle. Note that the gdImageBoundsSafe function now returns true only if the specified location is within the clipping rectangle. Of course, the default clipping area is the entire image. The behavior of existing gd applications does not change.
  • Support for fast drawing of antialiased lines and polygons, by Bright Fulton and Frank Faubert. To learn more about this feature, read about the gdImageSetAntiAliased function, which is used to set the foreground color for antialiasing, as well as the gdAntiAliased constant, which is passed to line- and polygon-drawing functions in place of a color. This code does not currently support an alpha channel component in the specified foreground color, or in the existing background image, but does perform alpha blending against an opaque background. Also see the gdImageSetAntiAliasedDontBlend function, which allows the specification of a special background color that should never be blended with the foreground.
  • Fixes to color mapping in gdImageCopyMergeGray. Thanks to Philip Warner.
  • gdImageStringFTEx now supports explicit specification of the desired character mapping. This is useful when a font offers more than one of Unicode, Shift_JIS, and Big5.
  • The PNG compression level can now be specified when writing PNG images. See the new gdImagePngEx, gdImagePngEx, gdImagePngCtxEx, and gdImagePngPtrEx functions.
  • The annotate utility builds without error in the absence of freetype, although of course it is not useful without freetype.
  • Thorben Kundinger fixed a bug relating to the use of palette-based images as brushes when drawing on truecolor images.
  • Michael Schwartz corrected a problem with his code for drawing thick lines.
  • Prior to 2.0.12, any alpha channel component in the destination image was ignored when drawing with alpha blending in effect (see gdImageAlphaBlending). 2.0.12 correctly preserves an appropriate proportion of the alpha component of the destination, just as it preserves an appropriate proportion of the red, green and blue components, depending on the opacity of the foreground. Thanks to Frank Warmerdam for pointing out the issue.
  • Memory leaks on failed attempts to load fonts in gdImageStringFTEx were corrected. Thanks to Frank Faubert.
  • The impact of kerning is now correctly included in the calculation of the bounding box returned by the freetype text routines. This issue was pointed out by several individuals.
  • Color problems with the gd2 file format routines were fixed by Steven Brown. These problems were due to the incorrect use of a signed integer.
  • Version 2.0.12 supports the gd file format correctly for truecolor images. Truecolor gd files created with earlier releases in the 2.0 series must be written again. The gd file format is used to quickly load an entire uncompressed image, typically an existing background to which additional material will be added; it is not a general purpose file format. More advanced capabilities are also available via the gd2 format. Thanks to Andreas Pfaller for reporting the problem.
  • Signed vs. unsigned problem caused misbehavior when attempting to load a bad JPEG image. Thanks to Geert Jansen.
  • Existing truecolor PNG images with simple single-color transparency are now loaded properly, thanks to Slaven Rezic.
  • The gdImageTrueColorToPalette function no longer attempts to preserve an alpha channel in the original. My attempt to do so resulted in significantly inferior output even if no alpha channel was present in the original. Thanks to Barend Gehrels for submitting a new adaptation of Tom Lane's jquant2.c which does a very high-quality job of palette conversion. Thanks also to Steven Brown, who submitted patches allowing a single 100% transparent color in the original truecolor image to be preserved. In practice, more complex alpha channels in palettes are ill-supported and difficult to allocate skillfully.

What's new in version 2.0.11?

  • Support for the "gd2" file format, which allows fast loading of all or only part of an existing image, has been properly debugged for use with truecolor images. (Palette images already worked properly, except for a bug when loading from a regular file with gdImageCreateFromGd2Part, which has also been fixed.) .gd2 files can be either compressed or uncompressed, and they allow useful tricks such as fast loading of a 500x500 pixel region of a 6000x3000 pixel image, without uncompressing all of the image. .gd2 is NOT a general purpose file format and should only be used where quick loading of a background image or subset of a larger image is required. For more information, see gdImageGd2, gdImageCreateFromGd2, and gdImageCreateFromGd2Part.
  • The gd2topng utility has been extended to support extraction of only part of an image from a .gd2 file. This is both a demonstration and a practical tool.
  • Additional configure improvements by Lars Hecking.

What's new in version 2.0.10?

  • gdImageLine now clips to the edges of the image before drawing lines, which greatly improves performance when many lines extend outside or are entirely outside the actual image. Thanks to Nick Atty for this code.
  • gdImageBoundsSafe is replaced with a macro when called internally; this improves the performance of gdImageSetPixel and gdImageGetPixel a little bit, and therefore everything else as well. Thanks to Nicky Atty for the idea.
  • Transparent indexes are handled properly with non-truecolor source images in gdImageCopy. Thanks to Frank Warmerdam.
  • floor() replaced with a cast to long in gdImageCopyResampled, for a roughly 35% performance boost. Thanks to John Buckman.
  • gdft.c builds correctly on WIN32 without patches.
  • Much faster gdImageCreateFromJpeg routines, thanks to Christian Aberger for more efficient pointer arithmetic.
  • gdtestft correctly builds without PNG tests if PNG support is not present. Thanks to Gabriele Verzeletti.

What's new in version 2.0.9?

  • Version 2.0.9 contains a fix to gdImageCopyResized which allows correct results when copying a palette-based image with a single transparent index into a truecolor image. Thanks to Thorben Kundinger.
  • More configure fixes from Lars Hecking. Thanks, Lars.

What's new in version 2.0.8?

  • Version 2.0.8 contains additional fixes to the 'configure' script, allowing a clean out-of-the-box build on more systems.
  • Version 2.0.8 adds the new gdImageCopyRotated function, which can rotate any rectangular image region by an arbitrary number of degrees.

What's new in version 2.0.7?

Version 2.0.7 corrects a problem which caused 'configure' to complain that the directory NONE was not found, in various places, causing the configuration process to stop. There are no code changes.

What's new in version 2.0.6?

  • Fixed a compilation problem with gdft.c. A declaration appeared after executable code, and gcc let it slide by, so it made it out the door. My apologies!
  • As penance, I have seen to it that the entire library now compiles cleanly with the -Wall, -ansi and -pedantic options enabled.

What's new in version 2.0.5?

  • libgd 2.0.5 INSTALLS IN /usr/local/lib BY DEFAULT. IF YOU WANT IT TO INSTALL IN /usr/lib, YOU MUST SPECIFY THIS at configure time using this syntax:

    ./configure --prefix=/usr

  • gd now uses GNU autoconf. This means that the provided configure script should be compatible with all standard GNU configure options and will figure out the correct settings for a much wider range of operating systems. Many, many thanks to Lars Hecking for taking care of this.
  • The gdImageStringFTEx function is now included, thanks to Wez Furlong. My apologies to Wez for the unreasonable amount of time this patch has sat in my queue.
  • Additional fixes from Wez Furlong.
  • Arithmetic cleanup by Doug Claar.
  • Corrections to loading and saving of alpha channel information in PNG files, by Andrew Hull.
  • gdImageTrueColorToPalette does not contain unneeded test code.
  • gdImageCopyResized works properly again when copying from a non-truecolor source.

What's new in version 2.0.4?

The following contributions from John Ellson:
  • Various test programs now compile in the absence of PNG support
  • gdIOCtx correctly calls gdFree rather than free
  • Various cleanups to pass -Wall without warnings
  • Support for Adobe-style Type 1 fonts (.pfa and .pfb files) via freetype
  • gdImageColorResolve and gdImageColorResolveAlpha will not attempt to resolve a color request to the transparent color index (for palette-based images)
  • Improved font search path support
  • Antialiased freetype text on palette images works properly when more than one image is created in a single program lifetime with different color indexes
  • Better threshold for two-color "mono" images
  • Memory leak fixes
  • Text rotation fix
  • More extensive default font path
  • fontwheeltest and fontsizetest test programs for freetype
And the following additional fixes:
  • configure now correctly detects and provides support for the Xpm library and its dependencies (Len Makin)

What's new in version 2.0.3?

  • The configure script has been extensively modified to work properly in tests with both Solaris and Linux. Other platforms should also work based on feedback received and integrated to date.
  • The --prefix option to configure works properly.
  • The annotate utility has been added. This is a very handy tool for adding freetype text to existing JPEGs. After make install, type annotate -h for more information. Thanks to Joel Dubiner.

What's new in version 2.0.2?

  • A "configure" script has been added. After wrestling with GNU autoconf for a while, I got tired of trying to make it detect libraries but accept their absence gracefully, and so on. Instead, I wrote a short Perl script which does the job and builds a reasonable Makefile. Those who find it doesn't detect their system's needs properly are welcome to contribute patches or the necessary commands.
  • Antialiased freetype text output now works properly in both truecolor and non-truecolor contexts! Hurrah! On a truecolor image it is possible, for instance, to draw antialiased text on an arbitrarily complex background with 50% alpha blending (transparency), and get the expected pretty results. Thanks to Joel Dubiner for his support of this work.
  • By default, alpha blending is now done within the library. Also, by default, alpha channel is not saved with PNG images. This means that programmers who try loading a JPEG, scribbling some pretty antialiased text on it, and saving the JPEG again will now get the results they expected. It also means that, by default, users will not run afoul of the fact that many web browsers don't properly support full PNG alpha channel.
  • Various submitted bug fixes have been incorporated.
  • Various other submitted changes have not been incorporated. Sorry. The interval between 2.0.1 and 2.0.2 was simply too long, and changes accumulated which were not mutually compatible. I'll do better in the future, especially with bug fixes.

What's new in version 2.0.1?

  • Workaround for a bug in gcc, apparently found in gcc 2.7.2 and up. I reproduced and fixed it while using gcc 2.9.5.2. The bug occurred only when the -g option was in use. This problem caused gcc to spew internal error messages unrelated to the correctness of the code in gd_gd2.c. Howard Jones was first to report it.
  • gdImageFilledEllipse documented and altered; no longer requires a superfluous style argument. Thanks to Francis James Franklin.
  • The Makefile now offers the correct syntax for optionally creating a static library. Thanks to Jean-Lous Regez, among others.
  • A nested comment, an attempt to return the value of a void function, and a potentially significant error in gdImageCopyResampled were fixed thanks to Joseph Shirley.
  • A bug preventing proper truecolor text rendering was fixed, thanks to Jason Gallagher.
  • gdImageStringFT (FreeType) should now work better against a transparent or semitransparent background, and should act in a manner consistent with the most recent gdImageAlphaBlending setting. Antialiasing is now done via the alpha channel mechanism if the image is a truecolor image.
  • Bugs in the output of gdImageArc and gdImageFilledArc were reported by Bruce Verderaime. A simple and correct but inefficient implementation has been substituted until fixes are contributed for the faster code, which is in gd_arc_f_buggy.c along with the test program that reproduces the bug(s).
  • gdImageFilledArc now offers additional style options, which can be combined to produce various effects.
  • Masahito Yamaga (ma@yama-ga.com) sent a patch to improve support for Japanese output via gdImageStringFT. He also added a new readme.jpn file.
  • Zillions of documentation fixes.

What's new in version 2.0?

  • Support for truecolor images! Version 2.0 can load truecolor PNGs with no loss of color information, and almost no loss of alpha channel information. Version 2.0 can also load truecolor JPEGs with as little loss as possible; however, bear in mind that JPEG is a lossy format, so repeated load/save cycles always reduce image quality. This is not a bug. To create a truecolor image from scratch, call the new gdImageCreateTrueColor function. The gdImageCreate function is still available to create palette images, and may also be referred to as gdImageCreatePalette.
  • Support for alpha channels! In addition to 24 bits of color information for each pixel (eight bits of red, green, and blue respectively), version 2.0 supports 7 bits of "alpha channel" information. This is used to determine exactly how transparent the pixel should be. There is also support for a full 7 bits of transparency for each individual palette index in a palette-based image. Please note that, as of this writing, only Macintosh Internet Explorer 5.x and Mozilla/Netscape 6.x display partial transparency properly.
  • The new gdImageAlphaBlending function allows for two different modes of drawing. In blending mode, the alpha channel component of the color supplied to all drawing functions, such as gdImageSetPixel, determines how much of the underlying color should be allowed to shine through. The resulting image is not transparent. In non-blending mode, drawing color is copied literally with the alpha channel information, resulting in a transparent image. Blending mode is not available when drawing on palette images.
  • The gdImageCopyResampled function provides "smooth" copying from a large image to a smaller one, using a weighted average of the pixels of the source area rather than selecting one representative pixel. This function is identical to gdImageCopyResized when the destination image is a palette image.
  • The gdImageTrueColorToPalette function converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library code, which is excellent. The code has been modified to preserve as much alpha channel information as possible in the resulting palette, in addition to preserving colors as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.
  • A very high degree of backwards compatibility with existing gd 1.x code has been maintained, at both the source code and binary level. Code which directly accesses the pixels array will fail only if it encounters an existing truecolor image, which may happen if the code attempts to open and modify an existing JPEG or truecolor PNG. Such code should be modified to check the trueColor flag of the gdImage structure, and refer to the tpixels array instead when it is set.
  • gd is now compiled and installed as a shared library. However, gd still does not use autoconf, because I (TBB) have very limited patience with autoconf. These days, most Unix systems provide a fairly POSIX-standard environment, and the provided Makefile is likely to work well if users read it and follow the instructions at the top.
  • Support for line thickness was added by Michael Schwartz. My apologies to him for sitting on his patches for so long. See the new gdImageSetThickness function, which affects all standard gd functions that draw lines and curves. In addition, Michael added a convenient gdImageEllipse function.
  • The new gdImageFilledArc function provides a straightforward way to draw filled arcs. Also, gdImageFilledEllipse is a convenient way to fill an ellipse without specifying starting and ending angles. Thanks go out to F J Franklin.
  • To put an end to the confusion, TrueType 1.x support has been removed in favor of TrueType 2.x support. The old gdImageStringTTF function simply invokes gdImageStringFT.
  • The specialized .gd and .gd2 file formats have been upgraded to support truecolor. New images written by the versions of these functions found in 2.0 will be rejected, with varying degrees of grace, by older versions of gd. THIS AFFECTS THE .GD and .GD2 FORMATS ONLY. IF YOU ARE CONFUSED BY THIS PARAGRAPH, IT PROBABLY DOESN'T APPLY TO ANYTHING YOU WILL EVER ENCOUNTER. Since these file formats are absolutely, positively *not* designed for distributing images, just for preprocessing them, this should not be a big problem. gd 2.0 should read old .gd and .gd2 files correctly.

What's new in version 1.8.4?

  • Add support for FreeType2 (John Ellson ellson@graphviz.org)
  • Add support for finding in fonts in a builtin DEFAULT_FONTPATH, or in a path from the GDFONTPATH environment variable.
  • remove some unused symbols to reduce compiler warnings
  • bugfix in size comparisons in gdImageCompare
  • REXX now mentioned
  • All memory allocation functions are now wrapped within the library; gdFree is exported and recommended for freeing memory returned by the gdImage(Something)Ptr family of functions.

What's new in version 1.8.3?

  • WBMP output memory leak fixed
  • #include <gd.h> corrected to #include "gd.h" in gd_wbmp.c
  • Documented the fact that the source and output images shouldn't match in the WBMP test except for black and white source images

What's new in version 1.8.2?

  • WBMP support debugged and improved by Johann Van den Brande
  • WBMP tests added to gdtest.c by Thomas Boutell
  • Use of platform-dependent 'install' command removed by Thomas Boutell
  • Comments added to Makefile warning users to juggle the order of the libraries if the linker complains; is there any portable way to do this automatically, short of using autoconf?
  • Documentation of gdImageCreateFromXpm corrected
  • Updated links to fast-moving, always dodging libpng and zlib websites

What's new in version 1.8.1?

  • Optional components no longer built by default (following the documentation)
  • JPEG code no longer requires inappropriate header files
  • Win32 patches from Joe Gregorio
  • 16-bit font support for bdftogd, from Honza Pazdziora

What's new in version 1.8?

  • Support for JPEG output, courtesy of Doug Becker
  • A link to Michael Bradbery's Pascal wrapper
  • Support for WBMP output, courtesy of Maurice Szmurlo
  • gdImageColorClosestHWB function based on hue, whiteness, blackness, superior to the regular gdImageColorClosest function, courtesy of Philip Warner
  • License clarification: yes, you can modify gd

Additional JPEG Information

Support for reading and writing JPEG-format images is courtesy of Doug Becker and the Independent JPEG Group / Thomas G. Lane. You can get the latest version of the IJG JPEG software from ftp://ftp.uu.net/graphics/jpeg/ (e.g., the jpegsrc.v6b.tar.gz file). You must use version 6b or later of the IJG JPEG software. You might also consult the JPEG FAQ at http://www.faqs.org/faqs/jpeg-faq/.

What's new in version 1.7.3?

Another attempt at Makefile fixes to permit linking with all libraries required on platforms with order- dependent linkers. Perhaps it will work this time.

What's new in version 1.7.2?

An uninitialized-pointer bug in gdtestttf.c was corrected. This bug caused crashes at the end of each call to gdImageStringTTF on some platforms. Thanks to Wolfgang Haefelinger.

Documentation fixes. Thanks to Dohn Arms.

Makefile fixes to permit linking with all libraries required on platforms with order- dependent linkers.

What's new in version 1.7.1?

A minor buglet in the Makefile was corrected, as well as an inaccurate error message in gdtestttf.c. Thanks to Masahito Yamaga.

What's new in version 1.7?

Version 1.7 contains the following changes:
  • Japanese language support for the TrueType functions. Thanks to Masahito Yamaga.
  • autoconf and configure have been removed, in favor of a carefully designed Makefile which produces and properly installs the library and the binaries. System-dependent variables are at the top of the Makefile for easy modification. I'm sorry, folks, but autoconf generated many, many confused email messages from people who didn't have things where autoconf expected to find them. I am not an autoconf/automake wizard, and gd is a simple, very compact library which does not need to be a shared library. I did make many improvements over the old gd 1.3 Makefile, which were directly inspired by the autoconf version found in the 1.6 series (thanks to John Ellson).
  • Completely ANSI C compliant, according to the -pedantic-errors flag of gcc. Several pieces of not-quite-ANSI-C code were causing problems for those with non-gcc compilers.
  • gdttf.c patched to allow the use of Windows symbol fonts, when present (thanks to Joseph Peppin).
  • extern "C" wrappers added to gd.h and the font header files for the convenience of C++ programmers. bdftogd was also modified to automatically insert these wrappers into future font header files. Thanks to John Lindal.
  • Compiles correctly on platforms that don't define SEEK_SET. Thanks to Robert Bonomi.
  • Loads Xpm images via the gdImageCreateFromXpm function, if the Xpm library is available. Thanks to Caolan McNamara.

What's new in version 1.6.3?

Version 1.6.3 corrects a memory leak in gd_png.c. This leak caused a significant amount of memory to be allocated and not freed when writing a PNG image.

What's new in version 1.6.2?

Version 1.6.2 from John Ellson adds two new functions:
  • gdImageStringTTF - scalable, rotatable, anti-aliased, TrueType strings using the FreeType library, but only if libttf is found by configure. We do not provide TrueType fonts. Obtaining them is entirely up to you.
  • gdImageColorResolve - an efficient alternative for the common code fragment:
    
          if ((color=gdImageColorExact(im,R,G,B)) < 0)
              if ((color=gdImageColorAllocate(im,R,G,B)) < 0)
                  color=gdImageColorClosest(im,R,G,B);
    

Also in this release the build process has been converted to GNU autoconf/automake/libtool conventions so that both (or either) static and shared libraries can be built.

What's new in version 1.6.1?

Version 1.6.1 incorporates superior PNG reading and writing code from Greg Roelofs, with minor modifications by Tom Boutell. Specifically, I altered his code to read non-palette images (converting them to palette images badly, by dithering them), and to tolerate palette images with types of transparency that gd doesn't actually support (it just ignores the advanced transparency features). Any bugs in this area are therefore my fault, not Greg's.

Unlike gd 1.6, users should have no trouble linking with gd 1.6.1 if they follow the instructions and install all of the pieces. However, If you get undefined symbol errors, be sure to check for older versions of libpng in your library directories!

What's new in version 1.6?

Version 1.6 features the following changes:

Support for 8-bit palette PNG images has been added. Support for GIF has been removed. This step was taken to completely avoid the legal controversy regarding the LZW compression algorithm used in GIF. Unisys holds a patent which is relevant to LZW compression. PNG is a superior image format in any case. Now that PNG is supported by both Microsoft Internet Explorer and Netscape (in their recent releases), we highly recommend that GD users upgrade in order to get well-compressed images in a format which is legally unemcumbered.

What's new in version 1.5?

Version 1.5 featured the following changes:
New GD2 format
An improvement over the GD format, the GD2 format uses the zlib compression library to compress the image in chunks. This results in file sizes comparable to GIFs, with the ability to access parts of large images without having to read the entire image into memory.

This format also supports version numbers and rudimentary validity checks, so it should be more 'supportable' than the previous GD format.

Re-arranged source files
gd.c has been broken into constituant parts: io, gif, gd, gd2 and graphics functions are now in separate files.

Extended I/O capabilities.
The source/sink feature has been extended to support GD2 file formats (which require seek/tell functions; seek must return 1 for success, 0 for failure), and to allow more general non-file I/O.

Better support for Lincoln Stein's Perl Module
The new gdImage*Ptr function returns the chosen format stored in a block of memory. This can be directly used by the GD perl module.

Added functions
gdImageCreateFromGd2Part - allows retrieval of part of an image (good for huge images, like maps),
gdImagePaletteCopy - Copies a palette from one image to another, doing it's best to match the colors in the target image to the colors in the source palette.
gdImageGd2, gdImageCreateFromGd2 - Support for new format
gdImageCopyMerge - Merges two images (useful to highlight part of an image)
gdImageCopyMergeGray - Similar to gdImageCopyMerge, but tries to preserve source image hue.
gdImagePngPtr, gdImageJpegPtr, gdImageWBMPPtr, gdImageGdPtr, gdImageGd2Ptr - return memory blocks for each type of image.
gdImageCreateFromPngCtx, gdImageCreateFromGdCtx, gdImageCreateFromGd2Ctx, gdImageCreateFromGd2PartCtx - Support for new I/O context.
NOTE: In fairness to Thomas Boutell, any bug/problems with any of the above features should probably be reported to Philip Warner.

What's new in version 1.4?

Version 1.4 features the following changes:
Fixed polygon fill routine (again)
Thanks to Kirsten Schulz, version 1.4 is able to fill numerous types of polygons that caused problems with previous releases, including version 1.3.
Support for alternate data sources
Programmers who wish to load a GIF from something other than a stdio FILE * stream can use the new gdImageCreateFromPngSource function.
Support for alternate data destinations
Programmers who wish to write a GIF to something other than a stdio FILE * stream can use the new gdImagePngToSink function.
More tolerant when reading GIFs
Version 1.4 does not crash when reading certain animated GIFs, although it still only reads the first frame. Version 1.4 also has overflow testing code to prevent crashes when reading damaged GIFs.

What's new in version 1.3?

Version 1.3 features the following changes:
Non-LZW-based GIF compression code
Version 1.3 contained GIF compression code that uses simple Run Length Encoding instead of LZW compression, while still retaining compatibility with normal LZW-based GIF decoders (your browser will still like your GIFs). LZW compression is patented by Unisys. We are currently reevaluating the approach taken by gd 1.3. The current release of gd does not support this approach. We recommend that you use the current release, and generate PNG images. Thanks to Hutchison Avenue Software Corporation for contributing the RLE GIF code.
8-bit fonts, and 8-bit font support
This improves support for European languages. Thanks are due to Honza Pazdziora and also to Jan Pazdziora . Also see the provided bdftogd Perl 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 gdImageString16 and gdImageStringUp16 routines are used.
Improvements to the "webpng" example/utility
The "webpng" utility is now a slightly more useful application. Thanks to Brian 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 you find a situation where polygon fills still fail to behave properly, please send code that demonstrates the problem, and a fix if you have one. Verifying the fix is important.
Row-major, not column-major
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 should not affect properly written gd applications, but applications that directly manipulate the pixels array will require changes.

What else do I need to use gd?

To use gd, you will need an ANSI C compiler. All popular Windows 95 and NT C compilers are ANSI C compliant. Any full-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. Ask your ISP why it is missing.

As of version 1.6, you also need the zlib compression library, and the libpng library. As of version 1.6.2, you can draw text using antialiased TrueType fonts if you also have the libttf library installed, but this is not mandatory. zlib is available for a variety of platforms from the zlib website. libpng is available for a variety of platforms from the PNG website.

You will also want a PNG 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. Netscape 4.04 and higher, and Microsoft Internet Explorer 4.0 or higher, both support PNG. Not every PNG-compatible viewer supports alpha channel transparency, which is why gd 2.0.2 and above do alpha blending in the library by default; it is possible to turn on the saving of alpha channel information to the file instead.

How do I get gd?

Binaries (DLL for Windows programmers):

Source Code:

How do I build gd?

Win32 DLL users: if you are using MSVC, use the provided batch file makemsvcimport.bat to make a bgd.lib import library corresponding to the provided bgd.dll. Copy bgd.dll to your application directory, or to your Windows sytem directory. In the settings of your MSVC project, you MUST choose the "multithreaded DLL" library option under "code generation." mingw32 and cygwin users can simply link with the provided libbgd.a stub library in order to use the DLL.
Building gd From the Source

In order to build gd, you must first unpack the archive you have downloaded. If you are not familiar with tar and gunzip (Unix) or ZIP (Windows), please consult with an experienced user of your system. Sorry, we cannot answer questions about basic Internet skills.

Unpacking the archive will produce a directory called "gd-2.0.20".

For Unix

cd to the 2.0.20 directory and type:

./configure

NOTE: BY DEFAULT, THE LIBRARY IS INSTALLED IN /usr/local/lib and the include files are installed in /usr/local/include. IF YOU ARE UPGRADING, you may wish to use:
./configure --prefix=/usr
Rather than just ./configure, before typing make and make install.

If all goes well, this will create a Makefile. If all does not go well -- for instance, if neither the the JPEG nor the PNG and ZLIB libraries are found -- you will need to install those libraries, then come back and run configure again.

If necessary, make changes to the resulting Makefile. Then, type "make". If there are no errors, follow this with "make install". Because gd 2.0 and above installs as a shared library, it is necessary to install the library properly before running gd-based programs.

If you get errors, type ./configure --help for more information about the available options. In the unlikely event that the GNU autoconf-produced configure script does not work well for you, you may wish to try configure.pl, a simple Perl script with similar but less complete capabilities. If all else fails, try renaming makefile.sample to Makefile. However, ./configure is almost always your best bet.

For Windows

Use the DLL version! See the paragraph at the beginning of this sectino. If you really want to compile it yourself for some strange reason, read on.

Create a project using your favorite programming environment. Copy all of the gd files to the project directory. Add gd.c to your project. Add other source files as appropriate. Learning the basic skills of creating projects with your chosen C environment is up to you. Alternatively, use the free mingw32 or cygwin tools, which may prove to be compatible with the provided configure script.

If you wish to test the library, type "make test" AFTER you have successfully executed "make install". This will build several test programs, including "gddemo". (Not all of these programs are expected to print completely successful messages, depending on the nature of the image formats with which some of the tests are tried; for instance, WBMP is a black and white format, so loss of color information is expected there.) Run gddemo to see some of the capabilities of gd. Run gdtestft to play with the freetype support, if you have built gd with it and have access to truetype fonts.

gddemo should execute without incident, creating the file demoout.png. (Note there is also a file named demoin.png, which is provided in the package as part of the demonstration.)

Display demoout.png in your PNG viewer. The image should be 128x128 pixels and should contain an image of the space shuttle with quite a lot of graphical elements drawn on top of it.

(If you are missing the demoin.png file, the other items should appear anyway.)

Look at demoin.png to see the original space shuttle image which was scaled and copied into the output image.

gd basics: using gd in your program

gd lets you create PNG or JPEG images on the fly. To use gd in your program, include the file gd.h, and link with the gd library and the other required libraries; the syntax for most Unix flavors is:
-lgd -lpng -lz -ljpeg -lfreetype -lm
Assuming that all of these libraries are available.

If you want to use the provided simple fonts, include gdfontt.h, gdfonts.h, gdfontmb.h, gdfontl.h and/or gdfontg.h. For more impressive results, install FreeType 2.x and use the gdImageStringFT function. If you are not using the provided Makefile and/or a library-based approach, be sure to include the source modules as well in your project. (They may be too large for 16-bit memory models, that is, 16-bit DOS and Windows.)

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

/* Bring in gd library functions */
#include "gd.h"

/* Bring in standard I/O so we can output the PNG to a file */
#include <stdio.h>

int main() {
	/* Declare the image */
	gdImagePtr im;
	/* Declare output files */
	FILE *pngout, *jpegout;
	/* Declare color indexes */
	int black;
	int white;

	/* Allocate the image: 64 pixels across by 64 pixels tall */
	im = gdImageCreate(64, 64);

	/* Allocate the color black (red, green and blue all minimum).
		Since this is the first color in a new image, it will
		be the background color. */
	black = gdImageColorAllocate(im, 0, 0, 0);	

	/* Allocate the color white (red, green and blue all maximum). */
	white = gdImageColorAllocate(im, 255, 255, 255);	
	
	/* Draw a line from the upper left to the lower right,
		using white color index. */
	gdImageLine(im, 0, 0, 63, 63, white);	

	/* Open a file for writing. "wb" means "write binary", important
		under MSDOS, harmless under Unix. */
	pngout = fopen("test.png", "wb");

	/* Do the same for a JPEG-format file. */
	jpegout = fopen("test.jpg", "wb");

	/* Output the image to the disk file in PNG format. */
	gdImagePng(im, pngout);

	/* Output the same image in JPEG format, using the default
		JPEG quality setting. */
	gdImageJpeg(im, jpegout, -1);

	/* Close the files. */
	fclose(pngout);
	fclose(jpegout);

	/* Destroy the image in memory. */
	gdImageDestroy(im);
}
When executed, this program creates an image, allocates two colors (the first color allocated becomes the background color), draws a diagonal line (note that 0, 0 is the upper left corner), writes the image to PNG and JPEG files, and destroys the image.

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

Webpng: a more powerful gd example

Webpng is a simple utility program to manipulate PNGs from the command line. It is written for Unix and similar command-line systems, but should be easily adapted for other environments. Webpng allows you to set transparency and interlacing and output interesting information about the PNG in question.

webpng.c is provided in the distribution. Unix users can simply type "make webpng" to compile the program. Type "webpng" with no arguments to see the available options.

Function and type reference

Types

gdImage(TYPE)
The data structure in which gd stores images. gdImageCreate, gdImageCreateTrueColor and the various image file-loading functions return a pointer to this type, and the other functions expect to receive a pointer to this type as their first argument. It is reasonably safe to examine any of the members of this structure. It is also reasonably safe to modify individual pixels within the pixels or tpixels arrays. If the trueColor flag is set, the tpixels array is valid; otherwise the pixels array is valid.

The colorsTotal, red, green, blue, alpha and open arrays manage the palette. They are valid only when the trueColor flag is not set. The transparent value contains the palette index of the first transparent color as read-only information for backwards compatibility; gd 2.0 stores this information in the alpha array so that variable transparency can be supported for each palette entry. However, for truecolor images, transparent represents a single RGB color which is always 100% transparent, and this feature is generally supported by browsers which do not support full alpha channels.

typedef struct {
	/* Palette-based image pixels */
	unsigned char ** pixels;
	int sx;
	int sy;
	/* These are valid in palette images only. See also
	/* 'alpha', which appears later in the structure to
		preserve binary backwards compatibility */
	int colorsTotal;
	int red[gdMaxColors];
	int green[gdMaxColors];
	int blue[gdMaxColors]; 
	int open[gdMaxColors];
	/* For backwards compatibility, this is set to the
		first palette entry with 100% transparency,
		and is also set and reset by the 
		gdImageColorTransparent function. Newer
		applications can allocate palette entries
		with any desired level of transparency; however,
		bear in mind that many viewers, notably
		many web browsers, fail to implement
		full alpha channel for PNG and provide
		support for full opacity or transparency only. */
	int transparent;
	int *polyInts;
	int polyAllocated;
	struct gdImageStruct *brush;
	struct gdImageStruct *tile;	
	int brushColorMap[gdMaxColors];
	int tileColorMap[gdMaxColors];
	int styleLength;
	int stylePos;
	int *style;
	int interlace;
	/* New in 2.0: alpha channel for palettes. Note that only
		Macintosh Internet Explorer and (possibly) Netscape 6
		really support multiple levels of transparency in
		palettes, to my knowledge, as of 2/15/01. Most
		common browsers will display 100% opaque and
		100% transparent correctly, and do something 
		unpredictable and/or undesirable for levels
		in between. TBB */
	int alpha[gdMaxColors]; 
	/* Truecolor flag and pixels. New 2.0 fields appear here at the
		end to minimize breakage of existing object code. */
	int trueColor;
	int ** tpixels;
	/* Should alpha channel be copied, or applied, each time a
		pixel is drawn? This applies to truecolor images only.
		No attempt is made to alpha-blend in palette images,
		even if semitransparent palette entries exist. 
		To do that, build your image as a truecolor image,
		then quantize down to 8 bits. */
	int alphaBlendingFlag;
	/* Should the alpha channel of the image be saved? This affects
		PNG at the moment; other future formats may also
		have that capability. JPEG doesn't. */
	int saveAlphaFlag;
} gdImage;

The order of the structure members may appear confusing, but was chosen deliberately to increase backwards compatibility with existing gd 1.x-based binary code that references particular structure members.

gdImagePtr (TYPE)
A pointer to an image structure. gdImageCreate returns this type, and the other functions expect it as the first argument.
gdIOCtx (TYPE)
Most of the gd functions that read and write files, such as gdImagePng and , also have variants that accept a gdIOCtx structure; see gdImagePngCtx and gdImageCreateFromJpegCtx. Those who wish to provide their own custom routines to read and write images can populate a gdIOCtx structure with functions of their own devising to to read and write data. For image reading, the only mandatory functions are getC and getBuf, which must return the number of characters actually read, or a negative value on error or EOF. These functions must read the number of characters requested unless at the end of the file. For image writing, the only mandatory functions are putC and putBuf, which return the number of characters written; these functions must write the number of characters requested except in the event of an error. The seek and tell functions are only required in conjunction with the gd2 file format, which supports quick loading of partial images. The gd_free function will not be invoked when calling the standard Ctx functions; it is an implementation convenience when adding new data types to gd. For examples, see gd_png.c, gd_gd2.c, gd_jpeg.c, etc., all of which rely on gdIOCtx to implement the standard image read and write functions.
typedef struct gdIOCtx
{
  int (*getC) (struct gdIOCtx *);
  int (*getBuf) (struct gdIOCtx *, void *, int wanted);

  void (*putC) (struct gdIOCtx *, int);
  int (*putBuf) (struct gdIOCtx *, const void *, int wanted);

  /* seek must return 1 on SUCCESS, 0 on FAILURE. Unlike fseek! */
  int (*seek) (struct gdIOCtx *, const int);

  long (*tell) (struct gdIOCtx *);

  void (*gd_free) (struct gdIOCtx *);

} gdIOCtx;
gdFont (TYPE)
A font structure. Used to declare the characteristics of a font. Please see the files gdfontl.c and gdfontl.h for an example of the 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 single character in a font by examining the w and h members of the structure. If you will not be creating your own fonts, you will not need to concern yourself with the rest of the components of this structure.
typedef struct {
	/* # of characters in font */
	int nchars;
	/* First character is numbered... (usually 32 = space) */
	int offset;
	/* Character width and height */
	int w;
	int h;
	/* Font data; array of characters, one row after another.
		Easily included in code, also easily loaded from
		data files. */
	char *data;
} gdFont;
gdFontPtr (TYPE)
A pointer to a font structure. Text-output functions expect these as their second argument, following the gdImagePtr argument. Two such pointers are declared in the provided include files gdfonts.h and gdfontl.h.
gdPoint (TYPE)
Represents a point in the coordinate space of the image; used by gdImagePolygon and gdImageFilledPolygon.
typedef struct {
        int x, y;
} gdPoint, *gdPointPtr;
gdPointPtr (TYPE)
A pointer to a gdPoint structure; passed as an argument to gdImagePolygon and gdImageFilledPolygon.
gdFTStringExtra (TYPE)
A structure used to pass additional parameters to the gdImageStringFTEx function. See gdImageStringFTEx for the structure definition.
gdFTStringExtraPtr (TYPE)
A pointer to a structure used to pass additional parameters to the gdImageStringFTEx function. See gdImageStringFTEx for the structure definition.
gdSource (TYPE)
typedef struct {
        int (*source) (void *context, char *buffer, int len);
        void *context;
} gdSource, *gdSourcePtr;
Represents a source from which a PNG can be read. Programmers who do not wish to read PNGs from a file can provide their own alternate input mechanism, using the gdImageCreateFromPngSource function. See the documentation of that function for an example of the proper use of this type.
gdSink (TYPE)
typedef struct {
        int (*sink) (void *context, char *buffer, int len);
        void *context;
} gdSink, *gdSinkPtr;
Represents a "sink" (destination) to which a PNG can be written. Programmers who do not wish to write PNGs to a file can provide their own alternate output mechanism, using the gdImagePngToSink function. See the documentation of that function for an example of the proper use of this type.

Image creation, destruction, loading and saving

gdImageCreate(sx, sy) (FUNCTION)
gdImageCreate is called to create palette-based images, with no more than 256 colors. Invoke gdImageCreate with the x and y dimensions of the desired image. gdImageCreate returns a gdImagePtr to the new image, or NULL if unable to allocate the image. The image must eventually be destroyed using gdImageDestroy().
... inside a function ...
gdImagePtr im;
im = gdImageCreate(64, 64);
/* ... Use the image ... */
gdImageDestroy(im);
gdImageCreateTrueColor(sx, sy) (FUNCTION)
gdImageCreateTrueColor is called to create truecolor images, with an essentially unlimited number of colors. Invoke gdImageCreateTrueColor with the x and y dimensions of the desired image. gdImageCreateTrueColor returns a gdImagePtr to the new image, or NULL if unable to allocate the image. The image must eventually be destroyed using gdImageDestroy().

Truecolor images are always filled with black at creation time. There is no concept of a "background" color index.

... inside a function ...
gdImagePtr im;
im = gdImageCreateTrueColor(64, 64);
/* ... Use the image ... */
gdImageDestroy(im);
gdImageCreateFromJpeg(FILE *in) (FUNCTION)
gdImageCreateFromJpegCtx(gdIOCtx *in) (FUNCTION)

gdImageCreateFromJpeg is called to load truecolor images from JPEG format files. Invoke gdImageCreateFromJpeg with an already opened pointer to a file containing the desired image. gdImageCreateFromJpeg returns a gdImagePtr to the new truecolor image, or NULL if unable to load the image (most often because the file is corrupt or does not contain a JPEG image). gdImageCreateFromJpeg does not close the file. You can inspect the sx and sy members of the image to determine its size. The image must eventually be destroyed using gdImageDestroy(). The returned image is always a truecolor image.
gdImagePtr im;
... inside a function ...
FILE *in;
in = fopen("myjpeg.jpg", "rb");
im = gdImageCreateFromJpeg(in);
fclose(in);
/* ... Use the image ... */
gdImageDestroy(im);
gdImageCreateFromPng(FILE *in) (FUNCTION)
gdImageCreateFromPngCtx(gdIOCtx *in) (FUNCTION)

gdImageCreateFromPng is called to load images from PNG format files. Invoke gdImageCreateFromPng with an already opened pointer to a file containing the desired image. gdImageCreateFromPng returns a gdImagePtr to the new image, or NULL if unable to load the image (most often because the file is corrupt or does not contain a PNG image). gdImageCreateFromPng does not close the file. You can inspect the sx and sy members of the image to determine its size. The image must eventually be destroyed using gdImageDestroy().

If the PNG image being loaded is a truecolor image, the resulting gdImagePtr will refer to a truecolor image. If the PNG image being loaded is a palette or grayscale image, the resulting gdImagePtr will refer to a palette image. gd retains only 8 bits of resolution for each of the red, green and blue channels, and only 7 bits of resolution for the alpha channel. The former restriction affects only a handful of very rare 48-bit color and 16-bit grayscale PNG images. The second restriction affects all semitransparent PNG images, but the difference is essentially invisible to the eye. 7 bits of alpha channel resolution is, in practice, quite a lot.

gdImagePtr im;
... inside a function ...
FILE *in;
in = fopen("mypng.png", "rb");
im = gdImageCreateFromPng(in);
fclose(in);
/* ... Use the image ... */
gdImageDestroy(im);
gdImageCreateFromPngSource(gdSourcePtr in) (FUNCTION)
gdImageCreateFromPngSource is called to load a PNG from a data source other than a file. Usage is very similar to the gdImageCreateFromPng function, except that the programmer provides a custom data source.

The programmer must write an input function which accepts a context pointer, a buffer, and a number of bytes to be read as arguments. This function must read the number of bytes requested, unless the end of the file has been reached, in which case the function should return zero, or an error has occurred, in which case the function should return -1. The programmer then creates a gdSource structure and sets the source pointer to the input function and the context pointer to any value which is useful to the programmer.

The example below implements gdImageCreateFromPng by creating a custom data source and invoking gdImageCreateFromPngSource.

static int freadWrapper(void *context, char *buf, int len);

gdImagePtr gdImageCreateFromPng(FILE *in)
{
        gdSource s;
        s.source = freadWrapper;
        s.context = in;
        return gdImageCreateFromPngSource(&s);
}

static int freadWrapper(void *context, char *buf, int len)
{
        int got = fread(buf, 1, len, (FILE *) context);
        return got;
}
gdImageCreateFromGd(FILE *in) (FUNCTION)
gdImageCreateFromGdCtx(gdIOCtx *in) (FUNCTION)

gdImageCreateFromGd is called to load images from gd format files. Invoke gdImageCreateFromGd with an already opened pointer to a file containing the desired image in the gd file format, which is specific to gd and intended for very fast loading. (It is not intended for compression; for compression, use PNG or JPEG.) gdImageCreateFromGd returns a gdImagePtr to the new image, or NULL if unable to load the image (most often because the file is corrupt or does not contain a gd format image). gdImageCreateFromGd does not close the file. You can inspect the sx and sy members of the image to determine its size. The image must eventually be destroyed using gdImageDestroy().
... inside a function ...
gdImagePtr im;
FILE *in;
in = fopen("mygd.gd", "rb");
im = gdImageCreateFromGd(in);
fclose(in);
/* ... Use the image ... */
gdImageDestroy(im);
gdImageCreateFromGd2(FILE *in) (FUNCTION)
gdImageCreateFromGd2Ctx(gdIOCtx *in) (FUNCTION)

gdImageCreateFromGd2 is called to load images from gd2 format files. Invoke gdImageCreateFromGd2 with an already opened pointer to a file containing the desired image in the gd2 file format, which is specific to gd2 and intended for fast loading of parts of large images. (It is a compressed format, but generally not as good as maximum compression of the entire image would be.) gdImageCreateFromGd returns a gdImagePtr to the new image, or NULL if unable to load the image (most often because the file is corrupt or does not contain a gd format image). gdImageCreateFromGd2 does not close the file. You can inspect the sx and sy members of the image to determine its size. The image must eventually be destroyed using gdImageDestroy().
... inside a function ...
gdImagePtr im;
FILE *in;
in = fopen("mygd.gd2", "rb");
im = gdImageCreateFromGd2(in);
fclose(in);
/* ... Use the image ... */
gdImageDestroy(im);
gdImageCreateFromGd2Part(FILE *in, int srcX, int srcY, int w, int h) (FUNCTION)
gdImageCreateFromGd2PartCtx(gdIOCtx *in) (FUNCTION)

gdImageCreateFromGd2Part is called to load parts of images from gd2 format files. Invoked in the same way as gdImageCreateFromGd2, but with extra parameters indicating the source (x, y) and width/height of the desired image. gdImageCreateFromGd2Part returns a gdImagePtr to the new image, or NULL if unable to load the image. The image must eventually be destroyed using gdImageDestroy().

gdImageCreateFromXbm(FILE *in) (FUNCTION)
gdImageCreateFromXbm is called to load images from X bitmap format files. Invoke gdImageCreateFromXbm with an already opened pointer to a file containing the desired image. gdImageCreateFromXbm returns a gdImagePtr to the new image, or NULL if unable to load the image (most often because the file is corrupt or does not contain an X bitmap format image). gdImageCreateFromXbm does not close the file. You can inspect the sx and sy members of the image to determine its size. The image must eventually be destroyed using gdImageDestroy().
... inside a function ...
gdImagePtr im;
FILE *in;
in = fopen("myxbm.xbm", "rb");
im = gdImageCreateFromXbm(in);
fclose(in);
/* ... Use the image ... */
gdImageDestroy(im);
gdImageCreateFromXpm(char *filename) (FUNCTION)
gdImageCreateFromXbm is called to load images from XPM X Window System color bitmap format files. This function is available only if HAVE_XPM is selected in the Makefile and the Xpm library is linked with the application. Unlike most gd file functions, the Xpm functions require filenames, not file pointers. gdImageCreateFromXpm returns a gdImagePtr to the new image, or NULL if unable to load the image (most often because the file is corrupt or does not contain an XPM bitmap format image). You can inspect the sx and sy members of the image to determine its size. The image must eventually be destroyed using gdImageDestroy().
... inside a function ...
gdImagePtr im;
FILE *in;
in = fopen("myxpm.xpm", "rb");
im = gdImageCreateFromXpm(in);
fclose(in);
/* ... Use the image ... */
gdImageDestroy(im);
gdImageDestroy(gdImagePtr im) (FUNCTION)
gdImageDestroy is used to free the memory associated with an image. It is important to invoke gdImageDestroy before exiting your program or assigning a new image to a gdImagePtr variable.
... inside a function ...
gdImagePtr im;
im = gdImageCreate(10, 10);
/* ... Use the image ... */
/* Now destroy it */
gdImageDestroy(im);
void gdImageJpeg(gdImagePtr im, FILE *out, int quality) (FUNCTION)
void gdImageJpegCtx(gdImagePtr im, gdIOCtx *out, int quality) (FUNCTION)
gdImageJpeg outputs the specified image to the specified file in JPEG format. The file must be open for writing. Under MSDOS and all versions of Windows, it is important to use "wb" as opposed to simply "w" as the mode when opening the file, and under Unix there is no penalty for doing so. gdImageJpeg does not close the file; your code must do so.

If quality is negative, the default IJG JPEG quality value (which should yield a good general quality / size tradeoff for most situations) is used. Otherwise, for practical purposes, quality should be a value in the range 0-95, higher quality values usually implying both higher quality and larger image sizes.

If you have set image interlacing using gdImageInterlace, this function will interpret that to mean you wish to output a progressive JPEG. Some programs (e.g., Web browsers) can display progressive JPEGs incrementally; this can be useful when browsing over a relatively slow communications link, for example. Progressive JPEGs can also be slightly smaller than sequential (non-progressive) JPEGs.

... inside a function ...
gdImagePtr im;
int black, white;
FILE *out;
/* Create the image */
im = gdImageCreate(100, 100);
/* Allocate background */
white = gdImageColorAllocate(im, 255, 255, 255);
/* Allocate drawing color */
black = gdImageColorAllocate(im, 0, 0, 0);
/* Draw rectangle */
gdImageRectangle(im, 0, 0, 99, 99, black);
/* Open output file in binary mode */
out = fopen("rect.jpg", "wb");
/* Write JPEG using default quality */
gdImageJpeg(im, out, -1);
/* Close file */
fclose(out);
/* Destroy image */
gdImageDestroy(im);
void* gdImageJpegPtr(gdImagePtr im, int *size) (FUNCTION)
Identical to gdImageJpeg except that it returns a pointer to a memory area with the JPEG data. This memory must be freed by the caller when it is no longer needed. The caller must invoke gdFree(), not free(), unless the caller is absolutely certain that the same implementations of malloc, free, etc. are used both at library build time and at application build time. The 'size' parameter receives the total size of the block of memory.
void gdImagePng(gdImagePtr im, FILE *out)
void gdImagePngCtx(gdImagePtr im, gdIOCtx *out) (FUNCTION)
gdImagePng outputs the specified image to the specified file in PNG format. The file must be open for writing. Under MSDOS and all versions of Windows, it is important to use "wb" as opposed to simply "w" as the mode when opening the file, and under Unix there is no penalty for doing so. gdImagePng does not close the file; your code must do so.
... inside a function ...
gdImagePtr im;
int black, white;
FILE *out;
/* Create the image */
im = gdImageCreate(100, 100);
/* Allocate background */
white = gdImageColorAllocate(im, 255, 255, 255);
/* Allocate drawing color */
black = gdImageColorAllocate(im, 0, 0, 0);
/* Draw rectangle */
gdImageRectangle(im, 0, 0, 99, 99, black);
/* Open output file in binary mode */
out = fopen("rect.png", "wb");
/* Write PNG */
gdImagePng(im, out);
/* Close file */
fclose(out);
/* Destroy image */
gdImageDestroy(im);
void gdImagePngEx(gdImagePtr im, FILE *out, int level)
void gdImagePngCtxEx(gdImagePtr im, gdIOCtx *out, int level) (FUNCTION)
Like gdImagePng, gdImagePngEx outputs the specified image to the specified file in PNG format. In addition, gdImagePngEx allows the level of compression to be specified. A compression level of 0 means "no compression." A compression level of 1 means "compressed, but as quickly as possible." A compression level of 9 means "compressed as much as possible to produce the smallest possible file." A compression level of -1 will use the default compression level at the time zlib was compiled on your system.

For more information, see gdImagePng.

void* gdImagePngPtr(gdImagePtr im, int *size) (FUNCTION)
Identical to gdImagePng except that it returns a pointer to a memory area with the PNG data. This memory must be freed by the caller when it is no longer needed. The caller must invoke gdFree(), not free(), unless the caller is absolutely certain that the same implementations of malloc, free, etc. are used both at library build time and at application build time. The 'size' parameter receives the total size of the block of memory.
void* gdImagePngPtrEx(gdImagePtr im, int *size, int level) (FUNCTION)
Like gdImagePngPtr, gdImagePngPtrEx returns a pointer to a PNG image in allocated memory. In addition, gdImagePngPtrEx allows the level of compression to be specified. A compression level of 0 means "no compression." A compression level of 1 means "compressed, but as quickly as possible." A compression level of 9 means "compressed as much as possible to produce the smallest possible file." A compression level of -1 will use the default compression level at the time zlib was compiled on your system.

For more information, see gdImagePngPtr.

gdImagePngToSink(gdImagePtr im, gdSinkPtr out) (FUNCTION)
gdImagePngToSink is called to write a PNG to a data "sink" (destination) other than a file. Usage is very similar to the gdImagePng function, except that the programmer provides a custom data sink.

The programmer must write an output function which accepts a context pointer, a buffer, and a number of bytes to be written as arguments. This function must write the number of bytes requested and return that number, unless an error has occurred, in which case the function should return -1. The programmer then creates a gdSink structure and sets the sink pointer to the output function and the context pointer to any value which is useful to the programmer.

The example below implements gdImagePng by creating a custom data source and invoking gdImagePngFromSink.

static int stdioSink(void *context, char *buffer, int len)
{
	return fwrite(buffer, 1, len, (FILE *) context);
}

void gdImagePng(gdImagePtr im, FILE *out)
{
	gdSink mySink;
	mySink.context = (void *) out;
	mySink.sink = stdioSink;
	gdImagePngToSink(im, &mySink);
}
void gdImageWBMP(gdImagePtr im, int fg, FILE *out)
gdImageWBMPCtx(gdIOCtx *out) (FUNCTION)(FUNCTION)
gdImageWBMP outputs the specified image to the specified file in WBMP format. The file must be open for writing. Under MSDOS and all versions of Windows, it is important to use "wb" as opposed to simply "w" as the mode when opening the file, and under Unix there is no penalty for doing so. gdImageWBMP does not close the file; your code must do so.

WBMP file support is black and white only. The color index specified by the fg argument is the "foreground," and only pixels of this color will be set in the WBMP file. All other pixels will be considered "background."

... inside a function ...
gdImagePtr im;
int black, white;
FILE *out;
/* Create the image */
im = gdImageCreate(100, 100);
/* Allocate background */
white = gdImageColorAllocate(im, 255, 255, 255);
/* Allocate drawing color */
black = gdImageColorAllocate(im, 0, 0, 0);
/* Draw rectangle */
gdImageRectangle(im, 0, 0, 99, 99, black);
/* Open output file in binary mode */
out = fopen("rect.wbmp", "wb");
/* Write WBMP, with black as foreground */
gdImageWBMP(im, black, out);
/* Close file */
fclose(out);
/* Destroy image */
gdImageDestroy(im);
void* gdImageWBMPPtr(gdImagePtr im, int *size) (FUNCTION)
Identical to gdImageWBMP except that it returns a pointer to a memory area with the WBMP data. This memory must be freed by the caller when it is no longer needed. The caller must invoke gdFree(), not free(), unless the caller is absolutely certain that the same implementations of malloc, free, etc. are used both at library build time and at application build time. The 'size' parameter receives the total size of the block of memory.
void gdImageGd(gdImagePtr im, FILE *out) (FUNCTION)
gdImageGd outputs the specified image to the specified file in the gd image format. The file must be open for writing. Under MSDOS and all versions of Windows, it is important to use "wb" as opposed to simply "w" as the mode when opening the file, and under Unix there is no penalty for doing so. gdImagePng does not close the file; your code must do so.

The gd image format is intended for fast reads and writes of images your program will need frequently to build other images. It is not a compressed format, and is not intended for general use.

... inside a function ...
gdImagePtr im;
int black, white;
FILE *out;
/* Create the image */
im = gdImageCreate(100, 100);
/* Allocate background */
white = gdImageColorAllocate(im, 255, 255, 255);
/* Allocate drawing color */
black = gdImageColorAllocate(im, 0, 0, 0);
/* Draw rectangle */
gdImageRectangle(im, 0, 0, 99, 99, black);
/* Open output file in binary mode */
out = fopen("rect.gd", "wb");
/* Write gd format file */
gdImageGd(im, out);
/* Close file */
fclose(out);
/* Destroy image */
gdImageDestroy(im);
void* gdImageGdPtr(gdImagePtr im, int *size) (FUNCTION)
Identical to gdImageGd except that it returns a pointer to a memory area with the GD data. This memory must be freed by the caller when it is no longer needed. The caller must invoke gdFree(), not free(), unless the caller is absolutely certain that the same implementations of malloc, free, etc. are used both at library build time and at application build time. The 'size' parameter receives the total size of the block of memory.
void gdImageGd2(gdImagePtr im, FILE *out, int chunkSize, int fmt)
void gdImageGd2Ctx(gdImagePtr im, gdIOCtx *out, int chunkSize, int fmt) (FUNCTION)
gdImageGd2 outputs the specified image to the specified file in the gd2 image format. The file must be open for writing. Under MSDOS and all versions of Windows, it is important to use "wb" as opposed to simply "w" as the mode when opening the file, and under Unix there is no penalty for doing so. gdImageGd2 does not close the file; your code must do so.

The gd2 image format is intended for fast reads and writes of parts of images. It is a compressed format, and well suited to retrieving smll sections of much larger images. The third and fourth parameters are the 'chunk size' and format resposectively.

The file is stored as a series of compressed subimages, and the Chunk Size determines the sub-image size - a value of zero causes the GD library to use the default.

It is also possible to store GD2 files in an uncompressed format, in which case the fourth parameter should be GD2_FMT_RAW.

... inside a function ...
gdImagePtr im;
int black, white;
FILE *out;
/* Create the image */
im = gdImageCreate(100, 100);
/* Allocate background */
white = gdImageColorAllocate(im, 255, 255, 255);
/* Allocate drawing color */
black = gdImageColorAllocate(im, 0, 0, 0);
/* Draw rectangle */
gdImageRectangle(im, 0, 0, 99, 99, black);
/* Open output file in binary mode */
out = fopen("rect.gd", "wb");
/* Write gd2 format file */
gdImageGd2(im, out, 0, GD2_FMT_COMPRESSED);
/* Close file */
fclose(out);
/* Destroy image */
gdImageDestroy(im);
void* gdImageGd2Ptr(gdImagePtr im, int chunkSize, int fmt, int *size) (FUNCTION)
Identical to gdImageGd2 except that it returns a pointer to a memory area with the GD2 data. This memory must be freed by the caller when it is no longer needed. The caller must invoke gdFree(), not free(), unless the caller is absolutely certain that the same implementations of malloc, free, etc. are used both at library build time and at application build time. The 'size' parameter receives the total size of the block of memory.
void gdImageTrueColorToPalette(gdImagePtr im, int ditherFlag, int colorsWanted) (FUNCTION)
Converts a truecolor image to a palette-based image, using a high-quality two-pass quantization routine. If ditherFlag is set, the image will be dithered to approximate colors better, at the expense of some obvious "speckling." colorsWanted can be anything up to 256. If the original source image includes photographic information or anything that came out of a JPEG, 256 is strongly recommended. 100% transparency of a single transparent color in the original truecolor image will be preserved. There is no other support for preservation of alpha channel or transparency in the destination image.

For best results, don't use this function -- write real truecolor PNGs and JPEGs. The disk space gain of conversion to palette is not great (for small images it can be negative) and the quality loss is ugly. However, the version of this function included in version 2.0.12 and later does do a better job than the version included prior to 2.0.12.

Drawing Functions

void gdImageSetPixel(gdImagePtr im, int x, int y, int color) (FUNCTION)
gdImageSetPixel sets a pixel to a particular color index. Always use this function or one of the other drawing functions to access pixels; do not access the pixels of the gdImage structure directly.
... inside a function ...
gdImagePtr im;
int black;
int white;
im = gdImageCreate(100, 100);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Set a pixel near the center. */
gdImageSetPixel(im, 50, 50, white);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageLine(gdImagePtr im, int x1, int y1, int x2, int y2, int color) (FUNCTION)
gdImageLine is used to draw a line between two endpoints (x1,y1 and x2, y2). The line is drawn using the color index specified. Note that the color index can be an actual color returned by gdImageColorAllocate or one of gdStyled, gdBrushed or gdStyledBrushed.
... inside a function ...
gdImagePtr im;
int black;
int white;
im = gdImageCreate(100, 100);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Draw a line from the upper left corner to the lower right corner. */
gdImageLine(im, 0, 0, 99, 99, white);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageDashedLine(gdImagePtr im, int x1, int y1, int x2, int y2, int color) (FUNCTION)
gdImageDashedLine is provided solely for backwards compatibility with gd 1.0. New programs should draw dashed lines using the normal gdImageLine function and the new gdImageSetStyle function.

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

... inside a function ...
gdImagePtr im;
int black;
int white;
im = gdImageCreate(100, 100);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Draw a dashed line from the upper left corner to the lower right corner. */
gdImageDashedLine(im, 0, 0, 99, 99);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImagePolygon(gdImagePtr im, gdPointPtr points, int pointsTotal, int color) (FUNCTION)
gdImagePolygon is used to draw a polygon with the verticies (at least 3) specified, using the color index specified. See also gdImageFilledPolygon.
... inside a function ...
gdImagePtr im;
int black;
int white;
/* Points of polygon */
gdPoint points[3];
im = gdImageCreate(100, 100);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Draw a triangle. */
points[0].x = 50;
points[0].y = 0;
points[1].x = 99;
points[1].y = 99;
points[2].x = 0;
points[2].y = 99;
gdImagePolygon(im, points, 3, white);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageRectangle(gdImagePtr im, int x1, int y1, int x2, int y2, int color) (FUNCTION)
gdImageRectangle is used to draw a rectangle with the two corners (upper left first, then lower right) specified, using the color index specified.
... inside a function ...
gdImagePtr im;
int black;
int white;
im = gdImageCreate(100, 100);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Draw a rectangle occupying the central area. */
gdImageRectangle(im, 25, 25, 74, 74, white);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageFilledPolygon(gdImagePtr im, gdPointPtr points, int pointsTotal, int color) (FUNCTION)
gdImageFilledPolygon is used to fill a polygon with the verticies (at least 3) specified, using the color index specified. See also gdImagePolygon.
... inside a function ...
gdImagePtr im;
int black;
int white;
int red;
/* Points of polygon */
gdPoint points[3];
im = gdImageCreate(100, 100);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Allocate the color red. */
red = gdImageColorAllocate(im, 255, 0, 0);	
/* Draw a triangle. */
points[0].x = 50;
points[0].y = 0;
points[1].x = 99;
points[1].y = 99;
points[2].x = 0;
points[2].y = 99;
/* Paint it in white */
gdImageFilledPolygon(im, points, 3, white);
/* Outline it in red; must be done second */
gdImagePolygon(im, points, 3, red);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageFilledRectangle(gdImagePtr im, int x1, int y1, int x2, int y2, int color) (FUNCTION)
gdImageFilledRectangle is used to draw a solid rectangle with the two corners (upper left first, then lower right) specified, using the color index specified.
... inside a function ...
gdImagePtr im;
int black;
int white;
im = gdImageCreate(100, 100);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = int gdImageColorAllocate(im, 255, 255, 255);	
/* Draw a filled rectangle occupying the central area. */
gdImageFilledRectangle(im, 25, 25, 74, 74, white);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageArc(gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color) (FUNCTION)
gdImageArc 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 at 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 width and height being equal. e must be greater than s. Values greater than 360 are interpreted modulo 360.
... inside a function ...
gdImagePtr im;
int black;
int white;
im = gdImageCreate(100, 50);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Inscribe an ellipse in the image. */
gdImageArc(im, 50, 25, 98, 48, 0, 360, white);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageFilledArc(gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color, int style) (FUNCTION)
gdImageFilledArc 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 at the position specified by e. The arc is filled in the color specified by the second to last argument. A circle can be drawn by beginning from 0 degrees and ending at 360 degrees, with width and height being equal. e must be greater than s. Values greater than 360 are interpreted modulo 360. The last argument is a bitwise OR of the following possibilities:
  • gdArc
  • gdChord
  • gdPie (synonym for gdChord)
  • gdNoFill
  • gdEdged
gdArc and gdChord are mutually exclusive; gdChord just connects the starting and ending angles with a straight line, while gdArc produces a rounded edge. gdPie is a synonym for gdArc. gdNoFill indicates that the arc or chord should be outlined, not filled. gdEdged, used together with gdNoFill, indicates that the beginning and ending angles should be connected to the center; this is a good way to outline (rather than fill) a 'pie slice'.
... inside a function ...
gdImagePtr im;
int black;
int white;
im = gdImageCreate(100, 50);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Inscribe a filled pie slice in the image. */
gdImageFilledArc(im, 50, 25, 98, 48, 0, 45, white, gdArc);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageFilledEllipse(gdImagePtr im, int cx, int cy, int w, int h, int color) (FUNCTION)
gdImageFilledEllipse is used to draw an ellipse centered at the given point, with the specified width and height in pixels. The ellipse is filled in the color specified by the last argument.
... inside a function ...
gdImagePtr im;
int black;
int white;
im = gdImageCreate(100, 50);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Inscribe a filled ellipse in the image. */
gdImageFilledEllipse(im, 50, 25, 98, 48, white);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageFillToBorder(gdImagePtr im, int x, int y, int border, int color) (FUNCTION)
gdImageFillToBorder floods a portion of the image with the specified color, beginning at the specified point and stopping at the specified border color. For a way of flooding an area defined by the color of the starting point, see gdImageFill.

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

Note that gdImageFillToBorder is recursive. It is not the most naive implementation possible, and the implementation is expected 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 3.1 environments. (Of course, in a Unix or Windows 95/98/NT environment with a proper stack, this is not a problem at all.)

... inside a function ...
gdImagePtr im;
int black;
int white;
int red;
im = gdImageCreate(100, 50);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Allocate the color red. */
red = gdImageColorAllocate(im, 255, 0, 0);	
/* Inscribe an ellipse in the image. */
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);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageFill(gdImagePtr im, int x, int y, int color) (FUNCTION)
gdImageFill floods a portion of the image with the specified color, beginning at the specified point and flooding the surrounding region of the same color as the starting point. For a way of flooding a region defined by a specific border color rather than by its interior color, see gdImageFillToBorder.

The fill color can be gdTiled, resulting in a tile fill using another image as the tile. However, the tile image cannot be transparent. If the image you wish to fill with has a transparent color index, call gdImageTransparent on the tile image and set the transparent color index to -1 to turn off its transparency.

Note that gdImageFill is recursive. It is not the most naive implementation possible, and the implementation is expected 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, in a Unix or Windows 95/98/NT environment with a proper stack, this is not a problem at all.)

... inside a function ...
gdImagePtr im;
int black;
int white;
int red;
im = gdImageCreate(100, 50);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
/* Allocate the color white (red, green and blue all maximum). */
white = gdImageColorAllocate(im, 255, 255, 255);	
/* Allocate the color red. */
red = gdImageColorAllocate(im, 255, 0, 0);	
/* Inscribe an ellipse in the image. */
gdImageArc(im, 50, 25, 98, 48, 0, 360, white);
/* Flood-fill the ellipse. Fill color is red, and will replace the
	black interior of the ellipse. */
gdImageFill(im, 50, 50, red);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
void gdImageSetAntiAliased(gdImagePtr im, int c) (FUNCTION)
"Antialiasing" is a process by which jagged edges associated with line drawing can be reduced by blending the foreground color with an appropriate percentage of the background, depending on how much of the pixel in question is actually within the boundaries of the line being drawn. All line-drawing functions, such as gdImageLine and gdImagePolygon, will draw antialiased lines if the special "color" gdAntiAliased is used when calling them.

gdImageSetAntiAliased is used to specify the actual foreground color to be used when drawing antialiased lines. You may set any color to be the foreground, however as of version 2.0.12 an alpha channel component is not supported.

Antialiased lines can be drawn on both truecolor and palette-based images. However, attempts to draw antialiased lines on highly complex palette-based backgrounds may not give satisfactory results, due to the limited number of colors available in the palette. Antialiased line-drawing on simple backgrounds should work well with palette-based images; otherwise create or fetch a truecolor image instead.

You need not take any special action when you are finished with antialised line drawing.

... inside a function ...
gdImagePtr im, brush;
int black;
int blue;
im = gdImageCreate(100, 100);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
blue = gdImageColorAllocate(im, 0, 0, 255);
gdImageSetAntiAliased(im, blue);
/* Draw a smooth line from the upper left corner to the lower right corner. */
gdImageLine(im, 0, 0, 99, 99, gdAntiAliased);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
See also gdAntiAliased and gdSetAntiAliasedDontBlend.
void gdImageSetAntiAliasedDontBlend(gdImagePtr im, int c) (FUNCTION)
Normally, when drawing lines with the special gdAntiAliased "color," blending with the background to reduce jagged edges is the desired behavior. However, when it is desired that lines not be blended with one particular color when it is encountered in the background, the gdImageSetAntiAliasedDontBlend function can be used to indicate the special color that the foreground should stand out more clearly against.
... inside a function ...
gdImagePtr im, brush;
int black;
int blue;
int white;
im = gdImageCreate(100, 100);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
blue = gdImageColorAllocate(im, 0, 0, 255);
white = gdImageColorAllocate(im, 255, 255, 255);

gdImageSetAntiAliased(im, blue);
/* The portion of the line that crosses this white rectangle will
  not be blended smoothly */
gdImageSetAntiAliasedDontBlend(im, white);
gdImageFilledRectangle(im, 25, 25, 75, 75, white);
/* Draw a smooth line from the upper left corner to the lower right corner. */
gdImageLine(im, 0, 0, 99, 99, gdAntiAliased);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
See also gdAntiAliased and gdSetAntiAliased.
void gdImageSetBrush(gdImagePtr im, gdImagePtr brush) (FUNCTION)
A "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 be a single pixel. Any gd image can be used as a brush, and by setting the transparent color index of the brush image with gdImageColorTransparent, a brush of any shape can be created. All line-drawing functions, such as gdImageLine and gdImagePolygon, will use the current brush if the special "color" gdBrushed or gdStyledBrushed is used when calling them.

gdImageSetBrush is used to specify the brush to be used in a particular image. You can set any image to be the brush. If the brush image does not have the same color map as the first image, any colors missing from the first image will be allocated. If not enough colors can be allocated, the closest colors already available will be used. This allows arbitrary PNGs to be used as brush images. It also means, however, that you should not set a brush unless you will 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.

You need not take any special action when you are finished with a brush. As for any other image, if you will not be using the brush image for any further purpose, you should call gdImageDestroy. You must not use the color gdBrushed if the current brush has been destroyed; you can of course set a new brush to replace it.

... inside a function ...
gdImagePtr im, brush;
FILE *in;
int black;
im = gdImageCreate(100, 100);
/* Open the brush PNG. For best results, portions of the
	brush that should be transparent (ie, not part of the
	brush shape) should have the transparent color index. */
in = fopen("star.png", "rb");
brush = gdImageCreateFromPng(in);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
gdImageSetBrush(im, brush);
/* Draw a line from the upper left corner to the lower right corner
	using the brush. */
gdImageLine(im, 0, 0, 99, 99, gdBrushed);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
/* Destroy the brush image */
gdImageDestroy(brush);
void gdImageSetTile(gdImagePtr im, gdImagePtr tile) (FUNCTION)
A "tile" is an image used to fill an area with a repeated pattern. Any gd image can be used as a tile, and by setting the transparent color index of the tile image with gdImageColorTransparent, a tile that allows certain parts of the underlying area to shine through can be created. All region-filling functions, such as gdImageFill and gdImageFilledPolygon, will use the current tile if the special "color" gdTiled is used when calling them.

gdImageSetTile is used to specify the tile to be used in a particular image. You can set any image to be the tile. If the tile image does not have the same color map as the first image, any colors missing from the first image will be allocated. If not enough colors can be allocated, the closest colors already available will be used. This allows arbitrary PNGs to be used as tile images. It also means, however, that you should not set a tile unless you will actually use it; if you set a rapid succession of different tile images, you can quickly fill your color map, and the results will not be optimal.

You need not take any special action when you are finished with a tile. As for any other image, if you will not be using the tile image for any further purpose, you should call gdImageDestroy. You must not use the color gdTiled if 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;
int black;
im = gdImageCreate(100, 100);
/* Open the tile PNG. For best results, portions of the
	tile that should be transparent (ie, allowing the
	background to shine through) should have the transparent
	color index. */
in = fopen("star.png", "rb");
tile = gdImageCreateFromPng(in);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
gdImageSetTile(im, tile);
/* Fill an area using the tile. */
gdImageFilledRectangle(im, 25, 25, 75, 75, gdTiled);
/* ... Do something with the image, such as saving it to a file... */
/* Destroy it */
gdImageDestroy(im);
/* Destroy the tile image */
gdImageDestroy(tile);
void gdImageSetStyle(gdImagePtr im, int *style, int styleLength) (FUNCTION)
It is often desirable to draw dashed lines, dotted lines, and other variations on a broken line. gdImageSetStyle can be used to set any desired series of colors, including a special color that leaves the background intact, to be repeated during the drawing of a line.

To use gdImageSetStyle, create an array of integers and assign them 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 dashed line to be attractively drawn over an existing image).

Then, to draw a line using the style, use the normal gdImageLine function with the special color value gdStyled.

As of version 1.1.1, the style array is copied when you set the style, so you need not be concerned with keeping the array around indefinitely. This should not break existing code that assumes styles are not copied.

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

gdImagePtr im;
int styleDotted[2], styleDashed[6];
FILE *in;
int black;
int red;
im = gdImageCreate(100, 100);
/* Background color (first allocated) */
black = gdImageColorAllocate(im, 0, 0, 0);	
red = gdImageColorAllocate(im, 255, 0, 0);	
/* Set up dotted style. Leave every other pixel alone. */
styleDotted[0] = red;
styleDotted[1] = gdTransparent;
/* Set up dashed style. Three on, three off. */
styleDashed[0] = red;
styleDashed[1] = red;
styleDashed[2] = red;
styleDashed[3] = gdTransparent;
styleDashed[4] = gdTransparent;
styleDashed[5] = gdTransparent;
/* Set dotted style. Note that we have to specify how many pixels are
	in the style! */
gdImageSetStyle(im, styleDotted, 2);
/* Draw a line from the upper left corner to the lower right corner. */
gdImageLine(im, 0, 0, 99, 99, gdStyled);
/* Now the dashed line. */
gdImageSetStyle(im, styleDashed, 6);
gdImageLine(im, 0, 99, 0, 99, gdStyled);

/* ... Do something with the image, such as saving it to a file ... */

/* Destroy it */
gdImageDestroy(im);
void gdImageSetThickness(gdImagePtr im, int thickness) (FUNCTION)
gdImageSetThickness determines the width of lines drawn by the gdImageL