Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Part III. Getting Involved with the Code

Chapter 14. Working with Images


In this chapter, you learn the following:

• How to modify PHP to increase image-related functionality

• How to create a new image

• How to modify existing images


A standard installation of PHP has many built-in functions for dynamically creating and manipulating images. Popular uses include the creation of charts and graphs and the modifications of existing images to display watermarks. With a few adjustments, you can expand the functionality even more.

This chapter covers the basics of creating and manipulating images using PHP functions.

Understanding the Image-Creation Process

Creating an image with PHP is not like creating an image with a drawing program (for example, Sumo Paint, Corel DRAW, or Windows Draw): There’s no pointing and clicking or dragging buckets of color into a predefined space to fill your image. Similarly, there’s no Save As functionality, in which your drawing program automatically creates a GIF, JPEG, PNG, and so on, just because you ask it to do so.

Instead, you have to become the drawing application. As the programmer, you must tell the PHP engine what to do at each step along the way. You are responsible for using the individual PHP functions to define colors, draw and fill shapes, size and resize the image, and save the image as a specific file type. It’s not as difficult as it might seem, however, if you understand each step along the way and complete the tasks in order.


Note

The examples in this chapter are not the most exciting examples ever, but only so much can be printed in the pages of a book (especially when that book is printed in black and white). Rest assured that these examples cover the fundamental knowledge required to work with the image-related functions in PHP.



A Word About Color

When defining colors in your image-related scripts, you use the RGB color system. Using decimal values from 0 to 255 for each of the red, green, and blue (R, G, and B) entries, you can define a specific color. A value of 0 indicates no amount of that specific color, and a value of 255 indicates the highest amount of that color.

For example, the RGB value for pure red is (255,0,0) or the entire allocation of red values, no green, and no blue. Similarly, pure green has a value of (0,255,0), and pure blue has a value of (0,0,255). White has an RGB value of (255,255,255), and black has an RGB value of (0,0,0). A nice shade of purple has an RGB value of (153,51,153), and a light gray has an RGB value of (204,204,204). For reference, you can see a list of colors and their RGB values at http://en.wikipedia.org/wiki/Web_colors.


Necessary Modifications to PHP

Current versions of the PHP distribution include a bundled version of Thomas Boutell’s GD graphics library. The inclusion of this library eliminates the need to download and install several third-party libraries, but this library needs to be activated at installation time.

To enable the use of the GD library at installation time, Linux/UNIX users must add the following to the configure parameters when preparing to build PHP:

--with-gd

After running the PHP configure program again, you must go through the make and make install process as you did in Chapter 4, “Installing and Configuring PHP.” Windows users who want to enable GD simply have to activate php_gd2.dll as an extension in the php.ini file, as you learned in Chapter 4.

When using the GD library, you are limited to working with GIF files. Working with GIF files might suit your needs perfectly, but if you want to create JPEG or PNG files on Linux/UNIX, you must download and install the few libraries listed here and make some modifications to your PHP installation. (These libraries are included and enabled in a Windows installation.)

• JPEG libraries, from http://www.ijg.org/.

• PNG libraries, from http://www.libpng.org/pub/png/libpng.html.

• If you are working with PNG files, you should also install the zlib library, from http://www.zlib.net/.

Follow the instructions at these sites to install the libraries. After installation, Linux/UNIX users must again reconfigure and rebuild PHP by first adding the following to the PHP configure parameters (assuming that you want to use all three; if not, just add the applicable ones):

--with-jpeg-dir=[path to jpeg directory]
--with-png-dir=[path to PNG directory]
--with-zlib=[path to zlib directory]

After running the PHP configure program again, you need to go through the make and make install process as you did in Chapter 4. Your libraries should then be activated and ready for use.

Drawing a New Image

The basic PHP function used to create a new image is called ImageCreate(), but creating an image is not as simple as just calling the function. Creating an image is a stepwise process and includes the use of several different PHP functions.

Creating an image begins with the ImageCreate() function, but all this function does is set aside a canvas area for your new image. The following line creates a drawing area that is 300 pixels wide by 300 pixels high:

$myImage = ImageCreate(300,300);

With a canvas now defined, you should next define a few colors for use in that new image. The following examples define five such colors (black, white, red, green, and blue, respectively), using the ImageColorAllocate() function and RGB values:

$black = ImageColorAllocate($myImage, 0, 0, 0);
$white = ImageColorAllocate($myImage, 255, 255, 255);
$red  = ImageColorAllocate($myImage, 255, 0, 0);
$green = ImageColorAllocate($myImage, 0, 255, 0);
$blue = ImageColorAllocate($myImage, 0, 0, 255);


Note

In your script, the first color you allocate is used as the background color of the image. In this case, the background color will be black. You could also have named the variable $background_color or some other contextually meaningful name.


Now that you know the basics of setting up your drawing canvas and allocated colors, you can move on to learning to draw shapes and actually output the image to a web browser.

Drawing Shapes and Lines

Several PHP functions can assist you in drawing shapes and lines on your canvas:

• ImageEllipse() is used to draw an ellipse.

• ImageArc() is used to draw a partial ellipse.

• ImagePolygon() is used to draw a polygon.

• ImageRectangle() is used to draw a rectangle.

• ImageLine() is used to draw a line.

Using these functions requires thinking ahead because you must set up the points where you want to start and stop the drawing that occurs. Each of these functions uses x-axis and y-axis coordinates as indicators of where to start drawing on the canvas. You must also define how far along the x-axis and y-axis you want the drawing to occur.

For example, the following line draws a rectangle on the canvas beginning at point (15,15) and continuing on for 80 pixels horizontally and 140 pixels vertically, so that the lines end at point (95,155). In addition, the lines will be drawn with the color red, which has already been defined in the variable $red.

ImageRectangle($myImage, 15, 15, 95, 155, $red);

If you want to draw another rectangle of the same size but with white lines, beginning at the point where the previous rectangle stopped, you would use this code:

ImageRectangle($myImage, 95, 155, 175, 295, $white);

Finally, to add another red rectangle aligned with the first, but beginning at the rightmost point of the white rectangle, use the following:

ImageRectangle($myImage, 175, 15, 255, 155, $red);

Listing 14.1 shows the image-creation script so far, with a few more lines added to output the image to the web browser.

Listing 14.1 Creating a New Image


1:  <?php
2:  //create the canvas
3:  $myImage = ImageCreate(300,300);
4:
5:  //set up some colors for use on the canvas
6:  $black = ImageColorAllocate($myImage, 0, 0, 0);
7:  $white = ImageColorAllocate($myImage, 255, 255, 255);
8:  $red  = ImageColorAllocate($myImage, 255, 0, 0);
9:  $green = ImageColorAllocate($myImage, 0, 255, 0);
10: $blue = ImageColorAllocate($myImage, 0, 0, 255);
11:
12: //draw some rectangles
13: ImageRectangle($myImage, 15, 15, 95, 155, $red);
14: ImageRectangle($myImage, 95, 155, 175, 295, $white);
15: ImageRectangle($myImage, 175, 15, 255, 155, $red);
16:
17: //output the image to the browser
18: header ("Content-type: image/png");
19: ImagePng($myImage);
20:
21: //clean up after yourself
22: ImageDestroy($myImage);
23: ?>


Lines 18–19 output the stream of image data to the web browser by first sending the appropriate header() function, using the MIME type of the image being created. Then you use the ImageGif(), ImageJpeg(), or ImagePng() function as appropriate to output the data stream; this example outputs a PNG file. In line 22, you use the ImageDestroy() function to clear up the memory used by the ImageCreate() function at the beginning of the script.

Save this listing as imagecreate.php and place it in the document root of your web server. When accessed, it should look something like Figure 14.1, only in color.

image

Figure 14.1 A canvas with three drawn rectangles.

Using a Color Fill

The output of Listing 14.1 produced only outlines of rectangles. PHP has image functions designed to fill areas as well:

• ImageFilledEllipse() is used to fill an ellipse.

• ImageFilledArc() is used to fill a partial ellipse.

• ImageFilledPolygon() is used to fill a polygon.

• ImageFilledRectangle() is used to fill a rectangle.

You use these functions just like their nonfill counterparts. In Listing 14.2, the nonfill functions are replaced with functions designed to fill an area. In other words, only lines 13–15 have changed.

Listing 14.2 Creating a New Image with Color Fills


1:  <?php
2:  //create the canvas
3:  $myImage = ImageCreate(300,300);
4:
5:  //set up some colors for use on the canvas
6:  $black = ImageColorAllocate($myImage, 0, 0, 0);
7:  $white = ImageColorAllocate($myImage, 255, 255, 255);
8:  $red  = ImageColorAllocate($myImage, 255, 0, 0);
9:  $green = ImageColorAllocate($myImage, 0, 255, 0);
10: $blue = ImageColorAllocate($myImage, 0, 0, 255);
11:
12: //draw some rectangles
13: ImageFilledRectangle($myImage, 15, 15, 95, 155, $red);
14: ImageFilledRectangle($myImage, 95, 155, 175, 295, $white);
15: ImageFilledRectangle($myImage, 175, 15, 255, 155, $red);
16:
17: //output the image to the browser
18: header ("Content-type: image/png");
19: ImagePng($myImage);
20:
21: //clean up after yourself
22: ImageDestroy($myImage);
23: ?>


Save this listing as imagecreatefill.php and place it in the document root of your web server. When accessed, it should look something like Figure 14.2, but again, in color.

image

Figure 14.2 A canvas with three drawn and filled rectangles.

Getting Fancy with Pie Charts

The previous examples were a little boring, but they introduced you to the basic process of creating images: defining the canvas, defining the colors, and then drawing and filling. You can use this same sequence of events to expand your scripts to create charts and graphs, using either static or dynamic data for the data points. Listing 14.3 draws a basic pie chart. Lines 1–10 look similar to the previous listings because they just set up the canvas size and colors to be used.

Listing 14.3 A Basic Pie Chart


1:  <?php
2:  //create the canvas
3:  $myImage = ImageCreate(300,300);
4:
5:  //set up some colors for use on the canvas
6:  $white = ImageColorAllocate($myImage, 255, 255, 255);
7:  $red  = ImageColorAllocate($myImage, 255, 0, 0);
8:
  $green = ImageColorAllocate($myImage, 0, 255, 0);
9:
  $blue = ImageColorAllocate($myImage, 0, 0, 255);
10:
11:  //draw a pie
12:  ImageFilledArc($myImage, 100, 100, 200, 150, 0, 90, $red, IMG_ARC_PIE);
13:  ImageFilledArc($myImage, 100, 100, 200, 150, 90, 180 , $green,   IMG_ARC_PIE);
14:  ImageFilledArc($myImage, 100, 100, 200, 150, 180, 360 , $blue,   IMG_ARC_PIE);
15:
16:  //output the image to the browser
17:  header ("Content-type: image/png");
18:  ImagePng($myImage);
19:
20:  //clean up after yourself
21:  ImageDestroy($myImage);
22:  ?>


Because the first defined color is white, the color of the canvas will be white.

Lines 12–14 use the ImageFilledArc() function, which has several attributes:

• The image identifier

• The partial ellipse centered at x

• The partial ellipse centered at y

• The partial ellipse width

• The partial ellipse height

• The partial ellipse start point

• The partial ellipse end point

• Color

• Style

Look at line 14 from Listing 14.3:

14:  ImageFilledArc($myImage, 100, 100, 200, 150, 180, 360 , $blue,   IMG_ARC_PIE);

The arc should be filled with the defined color $blue and should use the IMG_ARC_PIE style. The IMG_ARC_PIE style is one of several built-in styles (actually, defined constants) used in the display; this one says to create a rounded edge.


Note

You can learn about all the predefined image-related constants in the PHP Manual, at http://us2.php.net/manual/en/image.constants.php.


Save this listing as imagecreatepie.php and place it in the document root of your web server. When accessed, it should look something like Figure 14.3, but in color.

image

Figure 14.3 A simple pie with slices.

You can extend the code in Listing 14.3 and give your pie a 3D appearance. To do so, define three more colors for the edge. These colors can be either lighter or darker than the base colors, as long as they provide some contrast. The following examples define lighter colors:

$lt_red = ImageColorAllocate($myImage, 255, 150, 150);
$lt_green = ImageColorAllocate($myImage, 150, 255, 150);
$lt_blue = ImageColorAllocate($myImage, 150, 150, 255);

To create the shading effect, you use a for loop to add a series of small arcs at the points (100,110) to (100,101), using the lighter colors as fill colors:

for ($i = 110;$i > 100;$i--) {
    ImageFilledArc ($myImage, 100, $i, 200, 150, 0, 90, $lt_red, IMG_ARC_PIE);
    ImageFilledArc ($myImage, 100, $i, 200, 150, 90, 180, $lt_green,   IMG_ARC_PIE);
    ImageFilledArc ($myImage, 100, $i, 200, 150, 180, 360, $lt_blue,   IMG_ARC_PIE);
}

Listing 14.4 shows the code used for a 3D pie.

Listing 14.4 A 3D Pie Chart


1:  <?php
2:  //create the canvas
3:  $myImage = ImageCreate(300,300);
4:
5:  //set up some colors for use on the canvas
6:  $white = ImageColorAllocate($myImage, 255, 255, 255);
7:  $red  = ImageColorAllocate($myImage, 255, 0, 0);
8:  $green = ImageColorAllocate($myImage, 0, 255, 0);
9:  $blue = ImageColorAllocate($myImage, 0, 0, 255);
10: $lt_red = ImageColorAllocate($myImage, 255, 150, 150);
11: $lt_green = ImageColorAllocate($myImage, 150, 255, 150);
12: $lt_blue = ImageColorAllocate($myImage, 150, 150, 255);
13:
14: //draw the shaded area
15: for ($i = 110;$i > 100;$i--) {
16:     ImageFilledArc ($myImage,100,$i,200,150,0,90,$lt_red,IMG_ARC_PIE);
17:     ImageFilledArc ($myImage,100,$i,200,150,90,180,$lt_green,IMG_ARC_PIE);
18:     ImageFilledArc ($myImage,100,$i,200,150,180,360,$lt_blue,IMG_ARC_PIE);
19: }
20:
21: //draw a pie
22: ImageFilledArc($myImage, 100, 100, 200, 150, 0, 90, $red, IMG_ARC_PIE);
23: ImageFilledArc($myImage, 100, 100, 200, 150, 90, 180 , $green, IMG_ARC_PIE);
24: ImageFilledArc($myImage, 100, 100, 200, 150, 180, 360 , $blue, IMG_ARC_PIE);
25:
26: //output the image to the browser
27: header ("Content-type: image/png");
28: ImagePng($myImage);
29:
30: //clean up after yourself
31: ImageDestroy($myImage);
32: ?>


Save this listing as imagecreate3dpie.php and place it in the document root of your web server. When accessed, it should look something like Figure 14.4, but in color.

image

Figure 14.4 A 3D pie, with slices.

These are just basic examples that show the power of some of the image-drawing and filling functions. In the next section, you learn how to manipulate existing images.

Modifying Existing Images

The process of creating images from other images follows the same essential steps as creating a new image—the difference lies in what acts as the image canvas. Previously, you created a new canvas using the ImageCreate() function. When creating an image from a new image, you use theImageCreateFrom*() family of functions.

You can create images from existing GIFs, JPEGs, PNGs, and plenty of other image types. The functions used to create images from these formats are called ImageCreateFromGif(), ImageCreateFromJpg(), ImageCreateFromPng(), and so forth. In the next example, you can see how easy it is to create a new image from an existing one. Figure 14.5 shows the base image.

image

Figure 14.5 The base image.

Listing 14.5 shows how to use an existing image as the canvas, which then has filled ellipses drawn on it.

Listing 14.5 Creating a New Image from an Existing Image


1:  <?php
2:  //use existing image as a canvas
3:  $myImage = ImageCreateFromPng("baseimage.png");
4:
5:  //allocate the color white
6:  $white = ImageColorAllocate($myImage, 255, 255, 255);
7:
8:  //draw on the new canvas
9:  ImageFilledEllipse($myImage, 100, 70, 20, 20, $white);
10: ImageFilledEllipse($myImage, 175, 70, 20, 20, $white);
11: ImageFilledEllipse($myImage, 250, 70, 20, 20, $white);
12:
13: //output the image to the browser
14: header ("Content-type: image/png");
15: ImagePng($myImage);
16:
17: //clean up after yourself
18: ImageDestroy($myImage);
19: ?>


Save this listing as imagefrombase.php and place it in the document root of your web server. When accessed, it should look something like Figure 14.6.

image

Figure 14.6 Drawing on an existing image.

The next example takes this process a few steps forward and uses some different image-modification functions. In this case, the existing images are four PNG images, each with a differently colored triangular slice on a gray background. In Listing 14.6, you stack these images on top of each other and blend them together at each step so that the gray background becomes transparent and the image beneath it shows through.

Listing 14.6 Stacking Images and Making Them Transparent


1:  <?php
2:  //select an image to start with
3:  $baseimage = ImageCreateFromPng("img1.png");
4:
5:  //loop through images #2 through the end
6:  for($i=2; $i <5; $i++) {
7:    //allocate the transparent color, and stack
8:    $myImage = ImageCreateFromPng("img".$i.".png");
9:    $gray = ImageColorAllocate($myImage, 185, 185, 185);
10:   ImageColorTransparent($myImage, $gray);
11:   ImageCopyMerge($baseimage,$myImage,0,0,0,0,150,150,100);
12: }
13:
14: //output the image to the browser
15: header ("Content-type: image/png");
16: ImagePng($baseimage);
17:
18: //clean up after yourself
19: ImageDestroy($baseimage);
20: ?>


In line 3, one of the images is selected to be the base image. In this case, it’s img1.png. The for loop in lines 8–11 handles the bulk of the work. Knowing that you have four images and that you are already using the first one as the base, that leaves three more images to be stacked and made transparent.

After the new layer is created on line 8, its gray areas are indicated as transparent, and it is merged on top of the base image. As the layers are stacked, the base image contains an increasing number of layers until the total number of four layers is reached. At that point, the image is sent to the browser in lines 15–16.

Save this listing as imagestacker.php and place it in the document root of your web server. When accessed, it should look something like Figure 14.7.

image

Figure 14.7 Stacked transparent images produce a composite.

Image Creation from User Input

In addition to creating images from other images and drawing images on your own, you can create images based on user input. No fundamental difference exists in how the scripts are created except for the fact that you gather values from a form instead of hard-coding them into your script.

Listing 14.7 creates an all-in-one form and script that asks for user input for a variety of attributes ranging from image size to text and background colors, as well as a message string. You are introduced to the imagestring() function, which is used to “write” a string onto an image.

Let’s get into the script, where lines 2–38 represent the user input form, and the remaining lines handle the image created according to user specifications.

Listing 14.7 Creating an Image from User Input


1:  <?php
2:  if (!$_POST) {
3:      //show form
4:  ?>
5:  <!DOCTYPE html>
6:  <html>
7:  <head>
8:  <title>Image Creation Form</title>
9:
10: <style type="text/css">
11: fieldset{border: 0; padding: 0px 0px 12px 0px;}
12: fieldset label  {margin-left: 24px;}
13: legend, label    {font-weight:bold;}
14: </style>
15:
16: </head>
17: <body>
18: <h1>Create an Image</h1>
19: <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
20:
21: <fieldset>
22: <legend>Image Size:</legend><br/>
23: <label for="w">W:</label>
24: <input type="text" id="w" name="w" size="5" maxlength="5" />
25: <label for="h">H:</label>
26: <input type="text" id="h" name="h" size="5" maxlength="5" />
27: </fieldset>
28:
29: <fieldset>
30: <legend>Background Color:</legend><br/>
31: <label for="b_r">R:</label>
32: <input type="text" id="b_r" name="b_r" size="3" maxlength="3" />
33: <label for="b_g">G:</label>
34: <input type="text" id="b_g" name="b_g" size="3" maxlength="3" />
35: <label for="b_b">B:</label>
36: <input type="text" id="b_b" name="b_b" size="3" maxlength="3" />
37: </fieldset>
38:
39: <fieldset>
40: <legend>Text Color:</legend><br/>
41: <label for="t_r">R:</label>
42: <input type="text" id="t_r" name="t_r" size="3" maxlength="3" />
43: <label for="t_g">G:</label>
44: <input type="text" id="t_g" name="t_g" size="3" maxlength="3" />
45: <label for="t_b">B:</label>
46: <input type="text" id="t_b" name="t_b" size="3" maxlength="3" />
47: </fieldset>
48:
49: <p><label for="string">Text String:</label>
50: <input type="text" id="string" name="string" size="35" /></p>
51:
52: <p><label for="font_size">Font Size:</label>
53: <select id="font_size" name="font_size">
54: <option value="1">1</option>
55: <option value="2">2</option>
56: <option value="3">3</option>
57: <option value="4">4</option>
58: <option value="5">5</option>
59: </select></p>
60:
61: <fieldset>
62: <legend>Text Starting Position:</legend><br/>
63: <label for="x">X:</label>
64: <input type="text" id="x" name="x" size="3" maxlength="3" />
65: <label for="y">Y:</label>
66: <input type="text" id="y" name="y" size="3" maxlength="3" />
67: </fieldset>
68:
69: <button type="submit" name="submit" value="create">Create Image</button>
70: </form>
71: </body>
72: </html>


The bulk of this code listing so far is just an HTML form that defines several fields to obtain the image specifications. You can see that lines 1–4 are the only PHP code in this listing so far, and those lines check to see whether the form has been submitted (if the $_POST superglobal exists). After that check has happened, we break out of PHP and just provide the code for the form, which is shown only if the form has not been submitted; you could have put this HTML in an echo statement within PHP, but there’s no reason to make the PHP compiler do the work if it doesn’t have to.

The form fields in lines 24 and 26 define the width and the height of the image you want to draw. Next, the code sets up form fields to obtain the RGB values for a background color (lines 32, 34, and 36) and a text color (lines 42, 44, and 46).


Tip

You could create drop-down list boxes containing values 0 through 255 for the red, green, and blue values. This would ensure that the user input was within the required range.


Line 50 contains a form field for the input string. This string will be drawn onto the background of the image in the text color specified. Lines 53–59 represent a drop-down list for the selection of the font size. The function used to draw text on a string uses five sizes, 1 through 5 (the higher the number, the larger the font), for the default fixed-width font installed on the server.


Note

You can specify fonts using the imageloadfont() and imagettftext() functions. Learn more at http://www.php.net/image.


Finally, lines 64 and 66 allow you to define the text starting position. The upper-left corner of the image area would be X position 0, Y position 0; 10 increments downward would be Y position 10, 10 increments to the right would be X position 10, and so forth.

If you stop the script here and close up the if...else statement and PHP block, you will see a form like Figure 14.8 when it’s loaded in your web browser.

image

Figure 14.8 User input form for image creation.

In only 23 more lines, you can finish this script and generate images with text strings, so take a look at the remainder of Listing 14.7.

Listing 14.7 (continued)


73: <?php
74: } else {
75:    //create image
76:    //create the canvas
77:    $myImage = ImageCreate($_POST['w'], $_POST['h']);
78:
79:    //set up some colors
80:    $background = ImageColorAllocate ($myImage, $_POST['b_r'],
81:        $_POST['b_g'], $_POST['b_b']);
82:    $text = ImageColorAllocate ($myImage, $_POST['t_r'],
83:        $_POST['t_g'], $_POST['t_b']);
84:
85:    // write the string at the top left
86:    ImageString($myImage, $_POST['font_size'], $_POST['x'],
87:        $_POST['y'], $_POST['string'], $text);
88:
89:    //output the image to the browser
90:    header ("Content-type: image/png");
91:    ImagePNG($myImage);
92:
93:    //clean up after yourself
94:    ImageDestroy($myImage);
95: }
96: ?>


The majority of lines 73–96 you’ve already seen, only this time it uses extracted elements from the $_POST superglobal to take the place of hard-coded values. Line 77 uses the width and height values from the form to set up the initial image. Lines 80–83 define two colors, $background and$text, using the appropriate RGB values provided by the form.


Note

The colors weren’t given actual color names in this script because there’s no way to know what the user input would create—you could call the color $red, but you would look stupid if the user defined it as 0,255,0 because that’s the RGB value for green. Instead, simply name the colors after their purpose, not their appearance.


Lines 86–87 represent the only new item in this script: the use of the ImageString() function. The six parameters for this function are the image stream ($myImage), the font size ($_POST['font_size']), the starting X and Y positions ($_POST['x'] and $_POST['y']), the string to be drawn ($_POST['string']), and the color in which to draw it ($text). Lines 90–91 output the image to the browser, and line 94 destroys and cleans up the image creation process.

If you save this file as imagestring.php, place it in the document root of the web server, and fill out the form, the output could look something like Figure 14.9. But quite likely your results will differ because there are many variables to play with.

image

Figure 14.9 Sample output from image creation form.

Try it yourself, using various sizes, colors, and text strings.

Using Images Created by Scripts

All the earlier scripts produce image output, but you call them as standalone scripts. Using the results of an image created by a script, within your HTML, is as simple as using the name of the script—not an image—in the src attribute of the img tag. For example:

<img src="NameOfScript.php" />

In Listing 14.8, you create a simple script to produce an image. An img tag then calls this image and the browser displays it.

To add some new functionality to the mix, this basic script loads and uses a custom font to display a text string as a graphic—much like the user-generated text in the previous section, except the font is fancier. The reasons for this will soon become clear.

First, create the image-generating script. Listing 14.8 shows an example.

Listing 14.8 Creating an Image with Custom Font and Text


1:  <?php
2:  //create the canvas
3:  $myImage = ImageCreate(150,25);
4:
5:  //set up some colors for use on the canvas
6:  $white = ImageColorAllocate($myImage, 255, 255, 255);
7:  $black = ImageColorAllocate($myImage, 0, 0, 0);
8:
9:  //load a font
10: $font = imageloadfont("hootie.gdf");
11:
12: // write the string
13: ImageString($myImage, $font, 0, 0, "CAPTCHA!", $black);
14:
15: //output the image to the browser
16: header ("Content-type: image/png");
17: ImagePng($myImage);
18:
19: //clean up after yourself
20: ImageDestroy($myImage);
21: ?>


Line 3 creates a canvas that is 150 pixels wide and 25 pixels high. This size is something commonly seen in a CAPTCHA. In fact, that’s part of what you’re creating here.


Tip

CAPTCHA is a graphical challenge-response test to determine whether a user is a human. You might have encountered a CAPTCHA when completing a form to leave a comment on a website or to participate in a discussion forum, or when creating a user account. The idea is that only a human can read alphanumeric text in an image. You can read more about CAPTCHAs at http://en.wikipedia.org/wiki/Captcha.


Lines 5–7 set up the colors available to this script: white as the background and black as another color. Line 10 loads a font, using the imageloadfont() function. You could also use the imagettftext() function if you want to use TrueType fonts. In this example, the hootie.gdf font is a freely available font that comes in a single file placed on the filesystem and then loaded by the function calling it.


Note

You can find the font used in this example, as well as several other free fonts, just by searching “free GDF font” or “free TrueType font” in Google or your search engine of choice.


Line 13 uses the font loaded in line 10 as part of the ImageString() function call. In this example, $font is in the second parameter, meaning that the font and font size of the included font package are used in this instance of the function. The starting X and Y positions are hard-coded as 0 in the third and fourth parameters, and the string to be drawn—"CAPTCHA!"—is also hard-coded. The color in which to draw this string is $black, the value in the final parameter.

Lines 16–17 output the stream of image data to the web browser by first sending the appropriate header() function and then using ImagePng() to output the data stream; this example outputs a PNG file. Line 20 uses the ImageDestroy() function to clear up the memory used by theImageCreate() function at the beginning of the script.

If you stop at this point, send the script to your web server, and simply load it in your browser window, it will display the CAPTCHA! in a custom font. But the purpose of this section is to show how to load this image with the img tag, and to do that you need a little HTML file. Listing 14.9contains an img tag that does just that.

Listing 14.9 Using Images Created by Scripts


1:  <!DOCTYPE html>
2:  <html>
3:  <head>
4:  <title>Using Images Created by Scripts</title>
5:  </head>
6:  </body>
7:  <h1>Generated Image Below...</h1>
8:  <img src="imagecustomfont.php" alt="generated image" />
9:  </body>
10: </html>


This little HTML file contains one line of interest: line 7. In line 7, you can see that the value of the src attribute of the img tag is the name of the script created in Listing 14.8: imagecustomfont.php. Name the HTML file something like useimage.html, and send both the HTML and the PHP script to your web server.

Open useimage.html in your web browser and you will see something like Figure 14.10—namely, CAPTCHA! in a custom font, which is actually displayed in a graphic.

image

Figure 14.10 Using images created by scripts.

If you were really using this script as part of a CAPTCHA system, you would make at least two additions to it: randomizing the string instead of hard-coding it, and saving the randomized string in a database table so that the input matching process can occur.

Summary

This chapter briefly introduced you to what you can do with images and PHP. Reading the “Image Functions” section of the PHP Manual, at http://www.php.net/image, is highly recommended, not only for a complete list of image-related functions, but also for examples and discussion about their use in your applications.

In this chapter, you learned about installing and using additional libraries for working with images. (The examples used PNGs, but you were given instructions for using GIFs and JPGs, as well.) You learned the basic steps for creating an image canvas and allocating color and for drawing and filling shapes. You learned that your drawing canvas can consist of an existing image and that you can merge layers so that a final image is a composite of the merged layers. In addition, you saw how simple it is to use input from users (in this case, from an HTML form) in your image-creation scripts and how to use scripts as image sources in HTML code.

Q&A

Q. How do I use dynamic data to create the slices of a pie chart?

A. When creating any image, the start points and drawing lengths do not need to be statically indicated—they can be variables whose values are determined by a database, user input, or calculations within the script. For example, this code creates a red, filled arc of 90°:

ImageFilledArc($myImage,50,50,100,50,0,90,$red,IMG_ARC_PIE);

You could set this up so that the red-filled arc at the top of the pie holds the percentage of the total for May Sales in a variable called $may_sales_pct. The line then becomes something like this:

ImageFilledArc($myImage,50,50,100,50,0,$may_sales_pct,$red,IMG_ARC_PIE);

The number then is filled in from the calculations or database queries in your script. Be sure to add code to verify that all your arcs add up to 360.

Workshop

The workshop is designed to help you review what you’ve learned and begin putting your knowledge into practice.

Quiz

1. What RGB values would you use for pure black and pure white?

2. How do you create a new, blank canvas that is 300 pixels wide and 200 pixels tall?

3. What function is used to draw a polygon? A filled polygon?

Answers

1. (0,0,0) is pure black, and (255,255,255) is pure white.

2. To create a new, blank canvas that is 300 pixels wide and 200 pixels tall, use the following:

$new_image = ImageCreate(300,200);

3. ImagePolygon() and ImageFilledPolygon()

Activities

1. Instead of creating a pie chart, use your drawing skills to create a bar chart with either vertical or horizontal bars, each 30 pixels wide and filled with the same color, but of different lengths. Make sure that there are 10 pixels of space between each bar.

2. Extend the functionality from the first step by adding a form front end to it, and allow users to enter numbers of their choice. Generate your bar chart from those numbers.