Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Dynamic bitmap graphics with PHP and gd

Jacek Artymiak (jacek@artymiak.com), Freelance author and consultant
Jacek Artymiak works as a freelance consultant, developer, and writer. Since 1991 he's been developing software for many commercial and free variants of the UNIX and BSD operating systems (AIX, HP-UX, IRIX, Solaris, Linux, FreeBSD, NetBSD, OpenBSD, and others), as well as for the MS-DOS, Microsoft Windows, Mac OS, and Mac OS X operating systems. Jacek specializes in business and financial application development, Web design, network security, computer graphics, animation, and multimedia. He's a prolific writer on technology subjects and the coauthor of Install, Configure, and Customize Slackware Linux (Prima Tech, 2000) and StarOffice for Linux Bible (IDG Books, 2000). Find many of Jacek's software projects at SourceForge.net.

Summary:  If your job requires writing such applications in PHP, then this tutorial will teach you how to generate dynamic bitmap images using PHP and the gd library. A picture is worth a thousand words, especially when it is used to illustrate business, financial, or scientific data. It is worth even more if you can generate it on demand and serve the latest information in the visual format.

Date:  07 May 2003
Level:  Introductory PDF:  A4 and Letter (185 KB | 22 pages)Get Adobe® Reader®

Activity:  8757 views
Comments:  

Before you start

About this tutorial

A picture is worth a thousand words, especially when it is used to illustrate business, financial, or scientific data. It is worth even more if it can be generated on demand, so it can serve the latest information in the visual format. If your job requires writing such applications in PHP, then this tutorial will teach you how to generate bitmap images using PHP and the gd library.

Objectives

By the end of this tutorial, you will be able to start writing your own scripts to generate bitmap images using PHP and the gd library. You will be able to more easily illustrate business, financial, and scientific data. Specifically, you learn:

  • Basics on setting up your PHP/gd system
  • Operating system-specific tips to facilitate setting up your own system
  • How-tos for testing your PHP/gd installation
  • Steps to prepare your canvas, color palette, and background fill/image
  • A primer on gd drawing primitives
  • Exercises to help render data-visualization results
  • Tips for choosing a file format
  • Instructions to embed your script into HTML documents

Prerequisites

None.

System requirements

You need:

  • Access to a good operating system. I consider the following good operating systems:
    • Linux
    • Free/Net/OpenBSD
    • Microsoft Windows NT/2000
    • Mac OS X

    Other UNIX-like operating systems are also acceptable as long as they can run Apache (http://httpd.apache.org/docs/install.html), PHP (http://www.php.net/manual/en/installation.php), and gd 1.8.x (http://www.boutell.com/gd/manual1.8.4.html) or gd2.x (http://www.boutell.com/gd/manual2.0.1.html).

  • A machine with a CPU clocked at 100 MHz or more
  • A machine with 32 MB of RAM or more
  • A 500-MB hard disk

Also, you can use a different HTTP server as long as it is supported by PHP (http://www.php.net/manual/en/installation.php). On top of that, the gd library will need the following additional support libraries: freetype2, zlib, libpng, and libjpeg6.


Tips for assembling a working PHP system

The easiest way to put together a working PHP setup for the purposes of this tutorial (and in many cases, for production use) is to use pre-compiled Apache, PHP, gd, and any additional libraries that gd may require.

Following is a list of such tips for some of the most popular operating systems:

  • FreeBSD. Use the ports system (http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/ports.html) to install the latest software, but make sure that you install Apache 1.3.x not Apache 2.x, unless PHP is ported to Apache 2.x by the time you read this tutorial. Then, install gd and other required libraries.
  • Linux. This varies from distribution to distribution. Users of Red Hat and other RPM-based distributions should install apache-1.3.26, php4, php4-gd, and any additional RPMs that will be required. Users of Debian-based distributions should follow the same route, but use DEBs. Similarly, users of Slackware and other TGZ-based distributions should use appropriate TGZ archives.
  • Apple Mac OS X. Apache is a part of the default installation, so you only need to start it and add PHP and the rest of the software. Apple offers a nice page with instructions (http://developer.apple.com/internet/macosx/php.html).
  • NetBSD. Use the packages system ()http://www.mclink.it/personal/MG2508/nbsdeng/chap-pack.html to install required software. (See notes for FreeBSD.)
  • OpenBSD. Apache is a part of the default installation, so you only have to download PHP and the rest of the software, which you can do with pkg_add php4-version-gd.tgz. If you are new to OpenBSD packages, read "The Ports and Packages collection" (http://www.openbsd.org/ports.html). Then, start Apache with apachectl start (must be done by the superuser) and you're set.
  • Microsoft Windows. You only need to install Apache binaries (http://www.apache.org/dist/httpd/binaries/win32/) if you do not have IIS installed. PHP, gd and the rest of the necessary libraries are also available as a binary distribution with a GUI installer (http://www.php.net/downloads.php).
  • Other operating systems. Either use pre-compiled packages or build software from sources.

Building required tools from sources

If you cannot find ready-made binaries for your system, you will have to build them from sources using an ANSI C/C++ compiler like GCC.

As for the sources of particular packages, you can find them here:

For details on building every package, see README or INSTALL files found in each package. You should build in the following order:

  1. zlib
  2. libpng
  3. libjpeg
  4. freetype2
  5. t1lib
  6. gd
  7. Apache
  8. PHP

Most of these tools can be built by following the standard UNIX routine:

$ ./configure
$ ./make
$ sudo ./make install


Additional tools

Additional software required to test your scripts includes a graphical Web browser. Ideally, it ought to be running on a machine other than the one generating graphics, so you can check whether your scripts are accessible to the outside world. All major browsers (Mozilla, Internet Explorer, Opera, and others) are able to handle such tasks. You will also need a plain text editor. In this case vi, emacs, TextPad, or BBEdit work equally well.


Testing your PHP/gd installation

When you have all required components installed, you can check if the support for gd is working. This is done with two simple scripts.

First, you create a general PHP test script:

<?php phpinfo(); ?>

Save the script as test.php (remember to save it in the document directory), change file access modes to read-only for all users with chmod 0444 test.php and request the script using the browser (for example, http://localhost/test.php). You should see a long table listing various PHP options. Do a search for gd and check for the --with-gd option and the gd section (support for gd ought to be enabled). If the browser reports errors, check the configuration of your HTTP server, PHP, and gd and try again.

Next, create a gd test script:

<?php header("Content-Type: image/jpeg");

    # Set the dimensions of the canvas
    $cw = 500;
    $ch = 300;

    # Create canvas
    $c = ImageCreate($cw, $ch);

    # Generate color palette
    for ($n = 0; $n <= 255; $n++) {
      $cols[$n] = ImageColorAllocate($c, $n, $n, $n);
    }

    # Create background
    ImageFilledRectangle($c, 0, 0, 600, 400, $cols[255]);

    # Display all characters in a font
    $font = 4;
    $dx = ImageFontWidth($font);
    $dy = ImageFontHeight($font);
    $x = ($cw / 2) - (16 * $dx);
    $y = ($ch / 2) - (4 * $dy);
    $m = 0;
    $z = 0;

    for ($n = 0; $n <= 7; $n++) {
      for ($m = 0; $m <= 31; $m++) {
        ImageChar($c, $font, $x + $dx * $m, $y, chr($z), $cols[0]);
        $z++;
      }
      $y = $y + $dy;
    }

    # Draw a nice thin border around the edges of the image
    ImageRectangle($c, 0, 0, $cw-1, $ch-1, $cols[0]);

    # Generate image
    ImageJPEG($c);
?>

Again, you need to make this script readable by all users, and request it using your browser. The result should be identical to the following:

The result of running gdtest.php

1 of 8 | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, Open source
ArticleID=136390
TutorialTitle=Dynamic bitmap graphics with PHP and gd
publish-date=05072003
author1-email=jacek@artymiak.com
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Try IBM PureSystems. No charge.