Adding text to images in real time with PHP

Using PHP and the GD library the task of manipulating images, editing them and even adding text before presenting it to the user becomes a simple feat. Since I had to make use of this tool recently while making “on-the-fly” cupons for a client, i decided to write this article showing how easy this can be done.

First Steps

Attention: verify that the GD library is installed using a phpinfo() command.

There are a few ways of outputting the image after finishing the process, for example:

  • Save the file to disc
  • Output image on screen (as an image, inside the HTML)
  • Output to screen (just the image code)

In this example we are going to output the image to a <img> tag inside the HTML code, but for this we must understand a little about how this structure fits together. Generally an image tag points to a “.jpg” or “.gif” file, but here we need it to point to a “.php” file. This file will be responsible for seeking the image, editing it (insert text) and outputting the raw image code that will be read by the <img> tag.

So as a result we will have three files: the main.php file, that will output our HTML code, the image.php file that will edit and output the image, and a img.jpg that will be our base image that we will add text to.

main.php

This is a simple and straight-through file with an image tag. The only twist here is that in the image src attribute we will include (via GET) the name that should be written on the image.

Get your certificate below<br>

<img src="imagem.php?nome=Rafael%20Dohms" alt="" />

imagem.php

This is where the magic begins, this file should retreive the original image, the input text, and join the two, outputting the image with the text in it. So let’s go at it step by step.

The first step is to load the image into a PHP resource, basically loading it into the memory. PHP has a few functions for this, depending on the image’s format: ImageCreateFromJPEG, ImageCreateFromGIF and so on …

$rImg = ImageCreateFromJPEG( "ex-img.jpg" );

Now comes the time to write the text to the image, but first we need to get some parameters ready. There are basically two ways to write text on an image, one char at a time or a whole string at once (imagechar ou imagestring). In our example we will use the string method, but both receive the same parameters varying only on the text to be written. Before invoking the mothod we should setup the color to be used.

To do this we use the imagecolorallocate that receives as values the image resource and the color in RGB format (3 numbers) . In this case we use a black color:

$color = imagecolorallocate($rImg, 0, 0, 0);

Now we can begin writing. The function imagestring receives these parameters, in this order:

  • image: the image resource
  • font: an interger, from 1 to 5 (default PHP font, the bigger the numb, the bigger the font size) or a system font
  • x: horizontal shift (coordinate)
  • y: vertical shift (coordinate)
  • string: text to be written
  • color: variable with the allocated color

Note that the x and y coordinates are relative to the top left of the image. Also, for this example we will be using the default PHP font, but generally any TTF font will do, as i’ll describe towards the end of the article.

This is our base image:

Basically, I’ll write my name in the reserved spot, taking all this into account I can calculate the coordinates removing 2 or 3 pixels from the top because of the font overhead. The text should also be urldecoded and then on to the function that looks like this:

imagestring( $rImg,5,126,22,urldecode($_GET['nome']),$cor );

Before we finish up we have to define our content-header indicatig that our content is a JPG image, and then we can output the image code using the imageJPEG, that will spit out our raw image code. This function can also receive a second parameter that will output the content into the indicated file.

header('Content-type: image/jpeg');
imagejpeg($rImg);

This is the final result:

And this is the final code:

&lt; ?php

//Carregar imagem
$rImg = ImageCreateFromJPEG("ex-img.jpg");

//Definir cor
$cor = imagecolorallocate($rImg, 0, 0, 0);

//Escrever nome
imagestring($rImg,5,126,22,urldecode($_GET['nome']),$cor);

//Header e output
header('Content-type: image/jpeg');
imagejpeg($rImg,NULL,100);

?&gt;

Using custom fonts

We can use custom fonts to write our text, like Arial, Verdana or even more exotic ones like Futura or any other font not present by default in typical systems.To use TrueType fonts we can use the imagettftext function that allows us to point a .ttf file of the font we wish to use, as we can see jus below:

$font = 'arial.ttf';
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
  • Pingback: Bookmarks de 17/03/2008()

  • joe

    Didn’t work for me. My GD Library is enabled.

  • Beauford

    OK, so what parts go in what file? Kind of leaves you hanging. An example of the final code would be great.

  • kookimebux

    Hello. And Bye. :)

  • http://www.frooweb.com MD

    Nice little tutorial you have here. For all of those that are a bit lost (i can see why) here is a bit of information that might clear up any confusion.

    1. You have two separate files – main.php, and imagem.php. In his writing, make sure you follow the separation.

    2. You will be calling the main.php file when you want to execute the app, not the imagem.php (that is just the file that processes the data, but your calling it from the main.php file so thats what you will be typing in your browser).

    3. Obviously make sure you have the corresponding image file in the proper location.

    4. On his "final code" you have to remove lines 1, and 16, and replace them with the proper open/close tags for php. Obviously this site encoded the characters incorrectly.

    Those are the only "obvious" issues that I can see people having trouble with, although there could be more, and id be happy to help anyone out (just shoot me a pm or contact me through the frooweb site).

    Overall, this is a pretty simple and straightforward method, and as long as your not expecting to do anything "over the top" this should be able to handle it :-) Good Luck!

    Also, Rafael, it would probably help a bit to include a .zip or something of the final example (even if its on a free host) this way users can see the final product. But regardless you did an excellent job, and im sure its much appreciated :-)

  • http://www.jeroenlappenschaar.nl Jeroen

    Thank you very much for this! Its very clear and was very helpfull.

  • http://www.google.com Neetryattarge

    very intresting

  • http://ranacseruet.blogspot.com endless beginning

    I am trying this. However not working, can you please tell why? no image rendering at all.

  • http://www.nukestudios.com Luke

    This is great. Thank you.

    For anyone using the custom font… this is what the variables needed are.
    // source, size, angle, x, y, colour, font, text