Specifications
This tells the browser how to interpret the data that follows.
In this case, we want to tell the browser that we are sending an image instead of the usual
HTML output. We can do this using the Header() function, which we have not yet discussed.
This function sends raw HTTP header strings. Another typical application of this is to do
HTTP redirects. These tell the browser to load a different page instead of the one requested.
They are typically used when a page has been moved. For example,
Header (“Location: http://www.domain.com/new_home_page.html “);
An important point to note when using the Header() function is that it cannot be executed if
an HTTP header has already been sent for the page. PHP will send an HTTP header automati-
cally for you as soon as you output anything to the browser. Hence, if you have any echo state-
ments, or even any whitespace before your opening PHP tag, the headers will be sent, and you
will get a warning message from PHP when you try to call
Header(). However, you can send
multiple HTTP headers with multiple calls to the
Header() function in the same script,
although they must all appear before any output is sent to the browser.
After we have sent the header data, we output the image data with a call to
ImagePng ($im);
This sends the output to the browser in PNG format. If you wanted it sent in a different format,
you could call ImageJPEG()—if JPEG support is enabled—or ImageGIF() —if you have an
older version of gd. You would also need to send the corresponding header first; that is, either
Header (“Content-type: image/jpeg”);
or
Header (“Content-type: image/gif”);
The second option you can use, as an alternative to all the previous ones, is to write the image
to a file instead of to the browser. You can do this by adding the optional second parameter to
ImagePNG() (or a similar function for the other supported formats):
ImagePNG($im, $filename);
Remember that all the usual rules about writing to a file from PHP apply (for example, having
permissions set up correctly).
Generating Images
C
HAPTER 19
19
G
ENERATING
IMAGES
409
24 7842 CH19 3/6/01 3:42 PM Page 409










