Current Location: Home> Latest Articles> PHP imagestring() Function Tutorial: Draw Horizontal Text on Images

PHP imagestring() Function Tutorial: Draw Horizontal Text on Images

gitbox 2025-07-18

Introduction to imagestring() Function

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:

  • $image: The image resource, usually created with imagecreatetruecolor() or imagecreate().
  • $font: The font to be used, a value from 1 to 5 representing built-in system fonts.
  • $x: X-coordinate of where the text should begin.
  • $y: Y-coordinate of where the text should begin.
  • $string: The actual text to be drawn.
  • $color: The color of the text, set via imagecolorallocate().

Create an Image Resource

Before using imagestring(), you must create an image resource. The following code creates a 500×500 pixel blank image:

$im = imagecreatetruecolor(500, 500);

Set Colors and Font

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

Draw Text onto the Image

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);

Full Example: Centered Text on Image

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);

Conclusion

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.