Current Location: Home> Latest Articles> How to Use the imagestring Function to Add Date and Timestamp to an Image

How to Use the imagestring Function to Add Date and Timestamp to an Image

gitbox 2025-09-18
<span><span><span class="hljs-meta">&lt;?php</span></span><span>
</span><span><span class="hljs-comment">// This is the PHP part before the article content, unrelated to the main text</span></span><span>
</span><span><span class="hljs-keyword">echo</span></span><span> </span><span><span class="hljs-string">"Welcome to this tutorial!"</span></span><span>;
</span><span><span class="hljs-meta">?&gt;</span></span><span>
<p><hr></p>
<p></span><?php<br>
/*<br>
Title: How to Use the imagestring Function to Add Date and Timestamp to an Image<br>
*/</p>
<p>// In PHP, the imagestring function can be used to draw simple text on an image.<br>
// We can combine it with the date function to get the current date and time and write it onto the image.</p>
<p>// 1. Create a blank image<br>
$width = 400;<br>
$height = 100;<br>
$image = imagecreatetruecolor($width, $height);</p>
<p>// 2. Allocate colors<br>
$background_color = imagecolorallocate($image, 255, 255, 255); // White background<br>
$text_color = imagecolorallocate($image, 0, 0, 0); // Black text</p>
<p>// 3. Fill background<br>
imagefilledrectangle($image, 0, 0, $width, $height, $background_color);</p>
<p>// 4. Get the current date and time<br>
$timestamp = date('Y-m-d H:i:s');</p>
<p>// 5. Add date and time to the image<br>
// Parameters: image, font size (1-5), X coordinate, Y coordinate, text content, color<br>
imagestring($image, 5, 10, 40, $timestamp, $text_color);</p>
<p>// 6. Output the image to the browser<br>
header('Content-Type: image/png');<br>
imagepng($image);</p>
<p>// 7. Free image memory<br>
imagedestroy($image);</p>
<p>/*<br>
Notes:</p>
<ul>
<li>
<p>imagestring is suitable for drawing simple text; for more font styles, use imagettftext.</p>
</li>
<li>
<p>X and Y coordinates can be adjusted according to image size to ensure the text appears in the right position.</p>
</li>
<li>
<p>The date function format can be customized, e.g., 'Y-m-d H:i:s' shows full date and time.<br>
*/</p>
</li>
</ul>
<p>?></p>
<p data-is-last-node="" data-is-only-node=""><?php<br>
// This is the PHP part at the end of the article, unrelated to the main text<br>
echo "End of the article, thank you for reading!";<br>
?><br>
</span>