Dealing with Dynamic Data
Now that you know how to create a simple image, you may be wondering "what next?". Well, here's where the real fun begins - dealing with data!
Let's create an image which will output the date, time and user's IP address.
<?php
Header( "Content-type: image/png");
$image = imagecreate(320,130);
$date = date ("F dS Y h:i a");
$ip = $_SERVER['REMOTE_ADDR'];
$fullip = "Your IP address is $ip.";
$black = ImageColorAllocate($image,0,0,0);
$red = ImageColorAllocate($image,204,0,0);
$white = ImageColorAllocate($image,255,255,255);
ImageFilledRectangle($image,0,0,320,130,$white);
ImageString($image, 14, 0, 0, "$fullip", $red);
ImageString($image, 12, 0, 24, "Time is $date", $black);
ImagePNG($image);
ImageDestroy($image);
?> |
The only new function in this image is ImageString(), which simply outputs text on to the image using a default system font (to use custom fonts,
see Imagettftext()). For example, to output the user's IP we use ImageString($image, 14, 0, 0, "$fullip", $red);
which outputs $fullip (as assigned in the beginning) to $image (our image), with font size 14, starting at top left (0,0).
The great thing about this image is that the output will change every time the script is called (namely, the time will) because we assign the time using:
$date = date ("F dS Y h:i a");, which grabs the system's current time.
Creating Images Based on User Input
It is even possible to create images based on the users' input.
Take a look at this script, for example:
| <?php Header( "Content-type: image/png"); $image = imagecreate(320,130);$text = $_GET['text'];$black = ImageColorAllocate($image,0,0,0); $white = ImageColorAllocate($image,255,255,255); ImageFilledRectangle($image,0,0,320,130,$white);ImageString($image, 12, 0, 0, "$text", $black);ImagePNG($image);ImageDestroy($image);?> |
Save this script and call it directly in the following manner: www.yourdomain.com/script.php?text=your_string_here.
The image outputted will have that text written on it!
If you have worked with HTTP variables before, you'll recognize that $text = $_GET['text']; is responsible for that.
Conclusion
As you can, the possibilities are endless and this article only started to cover the things you can do with PHP and GD.
For a full reference and list of functions that you may use, refer yourself to PHP.net's Image Function reference page.