How to Write text on image using PHP with Example

In this article, you'll be knowing on how to write text on image in PHP using GD Library.

Here is an example, Lets create a new image from given file or url using imagecreatefromjpeg method for JPG and imagecreatefrompng for PNG Files.

$image = imagecreatefromjpeg($image_path);

Allocate a background color and text color to the image created in the above step using imagecolorallocate method.

$bg_color = imagecolorallocate ($image, 255, 255, 255);
$textcolor = imagecolorallocate ($image, 0, 0, 0);

Now lets declare font size and the text to be added on the image with its width and height & draw a string horizontally using imagestring method.

$font = 14;
$string = ""; //You can declare your own text
$width = imagefontwidth($font) * strlen($string) ;
$height = imagefontheight($font) ;
$x = imagesx($image) - $width ;
$y = imagesy($image) - $height;
imagestring ($image, $font, $x, $y, $string, $textcolor);

To create a JPG file from the given image imagejpeg method is used

$output = imagejpeg($image);