When we are drawing images on the fly we have to tell the browser about the content we are sending to it. We can't display an image by telling the browser that we are sending text or html code. To this we have to use header declaration at the first line of data we send to the browser window.
header("Content-type: image/jpg");
Without this line at the starting of the data (not the starting of the page) if we send an image browser will display non recognized characters on the screen. So we have to tell browser that we are sending an image. We also can't send any text or data along with the image. So we will be using another window to display any graph or image not the existing window were some text or data is already there. We also can't mix both in the new window.
By default browser is set to display text only.
Let us use this to create an image and then display the same in a web page.
<?php
header ("Content-type: image/jpg");
///// Create the image ////////
$im = @ImageCreate (100,40)
or die ("Cannot Initialize new GD image stream");
$background_color = ImageColorAllocate ($im, 204, 204, 204); // Assign background color
$text_color = ImageColorAllocate ($im, 51, 51, 255); // text color is given
ImageString($im,5,10,10,'PLUS2NET',$text_color); // Random string from session added
ImageJpeg ($im); // image displayed
imagedestroy($im); // Memory allocation for the image is removed.
?>
Output is here
To display the above generated image we used this HTML code.
<img src=gd-imagestring-demo.php>
Integrated with other html code in a full web page.
This code dynamically loads an image generated by the test1.php script. The query string ?time=<?php echo time(); ?> appends a unique timestamp to the image URL using PHP's time() function.
We can also link to different domains.
Including time() in the query string prevents the browser from caching the image. Since time() returns the current UNIX timestamp (which changes every second), it ensures that a fresh version of the image is loaded each time the page is refreshed. Without this, the browser might serve a cached version of the image, which may not reflect the most recent updates from test1.php.
✅ Benefit: Ensures the image is dynamically refreshed and stays up to date. 🚀