For developers like Divyesh, one of the most popular features of PHP is real-time image generation. That is, we can create a new image canvas, "paint" it, and either save it to a file, or send it directly to the browser. In this article, Divyesh will show you how to create an image in real-time with PHP.
Generating Images on the Fly With PHP - Generating the random number (Page 5 of 7 )
Generating our random number is very easy. We will simply create a function named get_random which will return a random number between 1 and the built-in PHP function, getrandmax(). Getrandmax() is an implementation specific function, and returns the largest seed value available on the current system. Our get_random function looks like this:
$max = getrandmax();
return rand(1,$max) + rand(1,$max) ;
To actually place any piece of textual data onto our image, we use the imagestring function. The imagestring function takes six parameters, as shown below:
int imagestring (int im, int font, int x, int y, string s, int col)
im: A reference to an image canvas created using the imagecreate function
font: An integer value specifying the number of the font to draw the text in. If font is 1, 2, 3, 4 or 5, then a built-in font is used
x: The horizontal displacement from the left of the image where the text will be drawn from, measured in pixels.
y: The vertical displacement from the top of the image where the text will be drawn from, measured in pixels.
s: The text to be drawn on the image
col: The color that the text will be painted. A reference to a color created using the imagecolorallocate function.
The following code will use our get_random function to generate a random number. It will also use the imagestring function to draw that number onto our image canvas:
$number = get_random();
For your convenience, the complete PHP script to generate our image containing a random number is shown below:
Copy the code shown above into random_numer.php, save the file, and load it into your web browser. You should be presented with an image similar to the one below (remember that we are using a random number, so yours will be different to mine):
Actually displaying the image as part of a HTML page is simple. Instead of specifying the src attribute of an image as a filename, you specify the name of our PHP script, like this:
When the browser loads this image, it will call the random_number.php script, which would return our image as a stream of binary data. The browser would then write this binary data to the screen as the image.
One last thing I will discuss in this article is changing the font of the random number as it appears in our image. This step is optional, but demonstrates the flexibility of PHP and the GD library.