Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to draw a text string image horizontally by using imagestring() function in PHP?
The imagestring() function is a built-in PHP function used to draw a text string horizontally on an image. It requires the GD extension to be enabled for image manipulation.
Installation: Ensure PHP GD extension is installed and enabled in your PHP configuration.
Syntax
bool imagestring($image, $font, $x, $y, $string, $color)
Parameters
The imagestring() function accepts six parameters −
$image − An image resource created by functions like
imagecreate()orimagecreatetruecolor().$font − Font size ranging from 1 to 5 for built-in fonts (1 is smallest, 5 is largest).
$x − Horizontal position (X-coordinate) of the upper-left corner where text starts.
$y − Vertical position (Y-coordinate) of the upper-left corner where text starts.
$string − The text string to be drawn on the image.
$color − A color identifier created using
imagecolorallocate().
Return Value
Returns true on success or false on failure.
Example 1
Drawing multiple text strings with different font sizes −
<?php
// Create the size and image by using imagecreate() function
$img = imagecreate(700, 300);
// Set the background color of the image
$background_color = imagecolorallocate($img, 0, 0, 255);
// Set the text color of the image
$text_color = imagecolorallocate($img, 255, 255, 255);
// Function to create an image that contains the string
imagestring($img, 5, 180, 150, "Tutorialspoint", $text_color);
imagestring($img, 3, 160, 120, "Simply Easy Learning", $text_color);
header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
?>
Example 2
Creating an image with custom colors and single text string −
<?php
// Create the size of the image or blank image
$img = imagecreate(700, 300);
// Set the background color of the image
$background_color = imagecolorallocate($img, 122, 122, 122);
// Set the text color of the image
$text_color = imagecolorallocate($img, 255, 255, 0);
// Function to create an image that contains a string
imagestring($img, 4, 30, 60, "Tutorialspoint: Simply Easy Learning", $text_color);
header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
?>
Key Points
Font sizes range from 1 (smallest) to 5 (largest) for built-in fonts.
Coordinates (0,0) represent the top-left corner of the image.
Always use
imagedestroy()to free up memory after image processing.The function draws text horizontally only; use
imagestringup()for vertical text.
Conclusion
The imagestring() function provides a simple way to add horizontal text to images in PHP. It's ideal for creating basic text overlays, watermarks, or simple graphics with textual content.
