How to add text to an image with PHP GD library

Here is an example of how you can add text to an image using the PHP GD library:

// Create image resource
$image = imagecreatefromjpeg("image.jpg");

// Allocate colors
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);

// Add text to image
imagestring($image, 5, 10, 10, "Hello World!", $black);

// Output image
header("Content-type: image/jpeg");

// Free up memory

In this example, we first create an image resource using the imagecreatefromjpeg function, which takes the path to a JPEG image as an argument. Next, we allocate colors for the text using the imagecolorallocate function. Then, we use the imagestring function to add the text "Hello World!" to the image at position (10,10) using the black color. Finally, we output the image to the browser using the imagejpeg function and free up memory by destroying the image resource with imagedestroy.

Watch a course Learn object oriented PHP

You can change the function imagecreatefromjpeg to imagecreatefrompng to create the image resource from a png file.

You can also use imagettftext function to add text to image using a true type font.

imagettftext($image, $font_size, $angle, $x, $y, $text_color, $font_file, $text);

This function allows you to specify the font file, size, and angle of the text, as well as the x and y coordinates of the text on the image.


  • The first parameter is the image resource
  • Second parameter is font size
  • Third parameter is angle of text
  • Fourth and fifth parameter are x and y coordinates on the image
  • Sixth parameter is color of the text
  • Seventh parameter is the font file location
  • Eighth parameter is the text which needs to be added.