How to add text to image in PHP

This article is going to show you how to add text to an image in PHP. It’s not as hard as it sounds and I’ll also explain the different ways you can apply this technique for different purposes, depending on whether you want a different font for your text, or if it should appear at a specific position on the image.

You can also add text to an image using jQuery. But for this tutorial, we are not going to use client-side code. So, let’s dive into it.

How to add text to dynamic image?

The first thing we’ll need is the image that we want to put the text onto. We can create a blank canvas using paint or any other graphic editing program if needed, but for now, let’s just create a dynamic image using PHP and add text to it. Check the code first.

<?php

// Create a 400x300 image
$image = imagecreatetruecolor(400, 300);

//create color
$green = imagecolorallocate($image, 28, 101, 71);
$white = imagecolorallocate($image, 255, 255, 255);

// Set the background to green
imagefilledrectangle($image, 0, 0, 400, 300, $green);

//string that you want to add
$string = "CodeHasBug";
$fontSize = 5;

//text position on image
$x = 151;
$y = 138;

//add text to image
imagestring($image, $fontSize, $x, $y, $string, $white);

// Output to browser
header('Content-Type: image/png');

imagepng($image);
imagedestroy($image);

Output:

  • First, create a 400×300 image with imagecreatetruecolor() function.
  • Create two colors, i.e. green and white using imagecolorallocate().
  • Fill the green color to that image by using imagefilledrectangle($image, 0, 0, 400, 300, $green);
  • Set the x and y position value where the text will be shown.
  • Add the string to image i.e. imagestring($image, $fontSize, $x, $y, $string, $white);
  • Set the header Content-Type option to tell the browser this is an png image. You can also change the Content-Type option to “image/jpeg” to tell the browser the image is jpeg.
  • In order to change image to JPEG format, you also need to change imagepng($image); to imagejpeg($image);

If you have noticed, the font size is too small. The imagestring() method only supports font sizes between 1-5 and draws a string horizontally. In order to use a different font style and size, use imagettftext() instead.

How to get image coordinate manually using Paint?

If you notice, I have set $x = 151; and $y = 138;. But the question is how to get the value?

In order to find x and y values from any image, open the image in MS Paint. Now move the mouse pointer over the image where you want to show the text.

Now check on the status bar of MS Paint. You will get the coordinate from there.

How to add text to existing image with custom font?

In the above example, we don’t use any external image for that. Now we are going to insert text into an existing image and also use a custom font for this. So let’s check the code.

<?php

// Create Image From Existing Image
$image = imagecreatefromjpeg('grass.jpg');

//create color
$white = imagecolorallocate($image, 255, 255, 255);


//string that you want to add
$string = "CodeHasBug";

// Set Path to Font File
$fontPath = realpath('Pacifico-Regular.ttf');

//set font size
$fontSize = 60;

//text position on image
$x = 250;
$y = 330;

//add text to image
imagettftext($image, $fontSize, 0, $x, $y, $white, $fontPath, $string);

// Output to browser
header('Content-Type: image/jpeg');

imagejpeg($image);
imagedestroy($image);

Output:

Now let’s check the code step by step for a better understanding.

  • In imagecreatefromjpeg('grass.jpg') function, I have passed grass.jpg image file. If you want to create image from .png or from other formats, use the specific function. For example, to create an image from .png use imagecreatefrompng('grass.png').
  • Now download any font and store the font path into a variable. Here I am using Pacifico-Regular.ttf font.
  • The imagettftext() function accepts custom font as well size size.

Why imagettftext is not working?

Many users often encounter the problem that they are getting a blank image. In this case, you will not see any error message. So it is difficult for the user to understand where the real problem is?

To fix the problem, you need to comment a line i.e. //header('Content-Type: image/jpeg');. By doing that, the browser can’t understand this is an image file or not and you will see the error.

Warning: imagettftext(): Could not find/open font

So you can clearly see what’s going wrong here. In this case, the imagettftext() function could not find or open the specified font.

To fix this error you need to specify the absolute font path. That means if you use relative font path i.e. $fontPath = 'Pacifico-Regular.ttf';, it will give you the path like https://yourdomain.com/Pacifico-Regular.ttf. But you need the absolute path.

So use realpath() i.e. $fontPath = realpath('your-font.ttf');.

How to center text horizontally and vertically in Image?

I know, manually setting the text coordinates in the picture is a tedious task. But if the process is automatic then it will be accurate. Now let’s check the code.

<?php

// Create Image From Existing Image
$image = imagecreatefromjpeg('grass.jpg');

//create color
$white = imagecolorallocate($image, 255, 255, 255);


//string that you want to add
$string = "Center Text";

// Set Path to Font File
$font = realpath('Pacifico-Regular.ttf');

//set font size
$fontSize = 80;

// Get image dimensions
$image_width = imagesx($image);
$image_height = imagesy($image);

// Get center coordinates of image
$centerX = $image_width / 2;
$centerY = $image_height / 2;


// Get size of text
list($left, $bottom, $right, , , $top) = imageftbbox($fontSize, 0, $font, $string);


// Determine offset of text
$left_offset = ($right - $left) / 2;
$top_offset = ($bottom - $top) / 2;



// Generate coordinates
$x = $centerX - $left_offset;
$y = $centerY + $top_offset;



//add text to image
imagettftext($image, $fontSize, 0, $x, $y, $white, $font, $string);

//Output to browser
header('Content-Type: image/jpeg');

imagejpeg($image);
imagedestroy($image);

Output:

How to center text horizontally and vertically in Image

Lots of code already has been discussed. Now let’s check the rest of the code.

  • Get the width and height of the image by using imagesx() and imagesy() function.
  • Get center coordinates of the image by devide $image_width and $image_height with 2.
  • The imageftbbox() calculates and returns the bounding box in pixels for a FreeType text.
  • Here list() function will assign the data into multiple variables. For example, imageftbbox() returns an array with 8 elements. We will store the value like that list($left, $bottom, $right, , , $top)
  • Determine offset of text i.e. top an left position.
  • Now generate coordinates based on center coordinates and offset value and store it as x and y.

How to add text to image with line break?

Suppose you have a long string that needs some line breaks. But PHP GD library does not support line breaks. In this situation, you need to break the string depending on the image size. So here is the basic example and you can play with it as per your need.

<?php

// Create Image From Existing Image
$image = imagecreatefromjpeg('quote.jpg');

//create color
$white = imagecolorallocate($image, 255, 255, 255);

// Get image dimensions
$image_width = imagesx($image);
$image_height = imagesy($image);


//long string that you want to add
$string = "No matter what you’re going through, there’s a light at the end of the tunnel.";
$text = wordwrap($string, ($image_width/25));
$lines = explode("\n", $text);


// Set Path to Font File
$font = realpath('Pacifico-Regular.ttf');

//set font size
$fontSize = 35;
$lineHeight = 80;
$padding = 120;


$i = $padding + 50;
foreach($lines as $line){

	//add text to image
	imagettftext($image, $fontSize, 0, $padding, $i, $white, $font, $line);
	$i += $lineHeight;
}



//Output to browser
header('Content-Type: image/jpeg');

imagejpeg($image);
imagedestroy($image);

Output:

Let’s understand the code so that you can implement it with your project.

  • The function wordwrap() wraps the string to a given number of characters. In this case it will wrap the string based on image width i.e. wordwrap($string, ($image_width/25));
  • Now make an array by using explode() function. That means it will break the string into multiple parts using line-break (“\n”).
  • Here $lineHeight is the space between each lines.
  • The $padding is basically x position of the image.
  • Now loop through the lines and increament $i value with $lineHeight. Basically $i is y position of the image.

How to add a text watermark in an image using the PHP GD library?

Sometimes we need to add a watermark to an image. You can also add a watermark using HTML and CSS. But in this example, I am going to use the PHP GD library.

<?php

// Create Image From Existing Image
$image = imagecreatefromjpeg('grass.jpg');

//create color
$transparent = imagecolorallocatealpha($image, 255, 255, 255, 100);

//string that you want to add
$string = "CodeHasBug";

// Set Path to Font File
$font = realpath('Pacifico-Regular.ttf');

//set font size
$fontSize = 80;

// Get image dimensions
$image_width = imagesx($image);
$image_height = imagesy($image);

// Get center coordinates of image
$centerX = $image_width / 2;
$centerY = $image_height / 2;


// Get size of text
list($left, $bottom, $right, , , $top) = imageftbbox($fontSize, 0, $font, $string);


// Determine offset of text
$left_offset = ($right - $left) / 2;
$top_offset = ($bottom - $top) / 2;



// Generate coordinates
$x = $centerX - $left_offset;
$y = $centerY + $top_offset;



//add text to image
imagettftext($image, $fontSize, 45, $x + 100, $y + 100, $transparent, $font, $string);

//Output to browser
header('Content-Type: image/jpeg');

imagejpeg($image);
imagedestroy($image);
  • The imagecolorallocatealpha() will create alpha color.
  • Here I have set angle property 45 degree and also added 100 with $x and $y value. So that rotation start from bottom left of the image.

Conclusion

In this blog post, I’ve shown you how to add text to an existing image in PHP. I hope that the techniques and explanations provided will help you get started with your own projects! If you want more information on this topic, check out our previous posts. What interesting things have you done with this technique? Let me know by leaving a comment below!

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment