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 - Displaying our image (Page 4 of 7 )
Displaying our image in a web browser is a synch, and takes just two easy steps:
Telling the browser that we are outputting an image, and not the default HTML content type
Creating the actual image
Firstly, let me explain why we need to change the content type of our PHP script. By default, PHP is configured to send HTML output to the browser. The web server does this by sending a content-type = text/html header along with your HTML code. This tells the browser that it will be receiving HTML, and to process anything that comes from the server as pure HTML. Nothing else.
In our example, we donít want the browser to treat our page as HTML, because it doesnít contain any. Our page will simply spit out the results of our new image. We want the browser to render our image as a standard JPEG image file, so we change the content type using the header function, like this:
This line MUST be placed right at the top of your PHP script, before any output occurs for it to work correctly. There can be no spaces before this line, and it must be enclosed with the PHP <?php and ?> tags respectively.
Secondly, we will want to actually output our image to the web browser. We can do this by using the imagejpeg function. The imagejpeg function simply takes one parameter, which is a reference to an image canvas created using the imagecreate function:
So, just to recap, our complete image generation script is shown below. Create a new file named random_number.php. Copy the code shown below into random_number.php and run the script from your web browser.
When you run random_number.php from within your web browser, you should see a simple rectangle, like the one shown below:
If you donít see the rectangle in your browser, or if any errors occur, then make sure you have copied the code shown above exactly as it appears. Also, make sure there is no white space before the first <?php tag.
Now that weíve got our basic image out of the way, letís actually generate a random number to display as part of our image.