18.1 Creating an Image with GD


You want to create a new image, whether it is in GIF, PNG, or JPEG format.

Technique

Use the ImageCreate() function and then use the ImagePng() , ImageJpeg() , or ImageGif() function, depending on your system:

 <?php header("Content-type: image/gif"); $im = ImageCreate(100,20); $red = ImageColorAllocate($im, 255, 0, 0); $white  = ImageColorAllocate($im, 255, 255, 255); ImageString($im, 3, 3, 3, "YES!", $white); ImageGif($im); ImageDestroy($im);  #Free memory ?> 

Comments

If you run the preceding script, you should see something like the following (although the font might be different):

 YES! 

But what exactly are we doing? Let's go over this line by line:

Line 3 ” Print the header telling the Web browser that this is a GIF image.

Line 4 ” Create a GD image stream that can be manipulated by any of the other GD functions. The format of this image is not determined until we tell GD that it is a GIF and print it out on Line 10.

Line 6 ” Create the background color for the image and set it to red using the ImageColorAllocate() function.

Line 7 ” Create the foreground color for the image and set it to white by using the ImageColorAllocate() function.

Line 9 ” Draw a string to image $im using a built-in font at x-pixel location of 3 and a y-pixel location of 3. The contents of the string is "YES!" and the color of the string is white, denoted by the variable $white .

Line 10 ” Convert the image to a GIF and output it to the browser.

Line 12 ” Destroy the memory allocated for the GIF. This is done when the script executes anyway.

In the example, we use the ImageGif() function to convert the image, $im , to a GIF and then output it to the browser ( STDOUT ). However, if we want to save it to a file, we can provide an optional second argument, like so:

 <?php $filename = "some_image.gif"; $im = ImageCreate(150,40); $red = ImageColorAllocate($im, 255, 0, 0); $white  = ImageColorAllocate($im, 255, 255, 255); ImageString($im, 3, 4, 3, "Saved to $filename with GD", $white); ImageGif($im, $filename); ImageDestroy($im);   # Free memory associated with image ?> The image was written to <?php echo $filename; ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net