In PHP, imagestring() is a built-in function used to draw horizontal text on an image. It's commonly used for generating CAPTCHAs, labeling graphics, or displaying simple text on dynamically created images.
The basic syntax of the function is as follows:
bool imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color )
Here’s what each parameter means:
Before using imagestring(), you must create an image resource. The following code creates a 500×500 pixel blank image:
$im = imagecreatetruecolor(500, 500);
Next, define the text color, background color, and font:
$font = 4; // Built-in font size
$color = imagecolorallocate($im, 0, 0, 0); // Black text
$background = imagecolorallocate($im, 255, 255, 255); // White background
Once the image and colors are ready, you can draw text onto the image. This example draws “Hello world!” at coordinates (50, 50):
imagestring($im, $font, 50, 50, "Hello world!", $color);
The following complete example draws the text "Hello World!" at the center of the image and outputs it as a PNG file:
$im = imagecreatetruecolor(500, 500);
$white = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $white);
$font = 1;
$x = imagesx($im) / 2 - imagefontwidth($font) * strlen("Hello World!") / 2;
$y = imagesy($im) / 2 - imagefontheight($font) / 2;
imagestring($im, $font, $x, $y, "Hello World!", $red);
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
The imagestring() function is a simple yet powerful tool in PHP for rendering text onto images. It requires minimal setup and is ideal for tasks like creating verification codes, watermarking, or dynamic text output. By adjusting coordinates, fonts, and colors, developers can quickly generate effective image-based text outputs.