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

9 thoughts on “Adding text to images in real time with PHP

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

  2. 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 :-)

  3. 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

  4. What if the text comes from user input on another web page and needs to be wrapped so it all appears in the image? How would I accomplish that?

    • I'll ignore your multiple posts in order to get attention (with other names) and tell you that you need to figure out now much you can fit in the width of the image and chunk the string into lines with that amount. Try using a fixed size font like courier since other fonts will not match cahr widths and lead to invalid counts.

  5. Can I put the returned image in [a] tag like this:
    <a href="<?php createImage($text); ?>" rel="example1" title="a child">Grouped Photo

  6. If you are getting a broken image, download the image and open it in notepad. You will see a PHP error. Correct it.

  7. On the question: What if the text comes from user input on another web page and needs to be wrapped so it all appears in the image? How would I accomplish that? Did anyone get an ansswer?

    • Its just a string, you just need to pipe the user input into the proper variable and do some input filtering for security.

      • Can u give an example to this please Rafael? I have a piece of string tied to the pipe which is securely filtered…but seriously an example would be great :)

  8. I figured out how to make it work on my server.
    It works perfectly thank you!

    Question: How can we do this on an animated GIF?
    Question2: How do I add a text field form on main.php to allow the user to enter their own text and generate the image?

    Thank you so much!

  9. This frustrates bejebus out of me! 99% of people who write articles such this seem to go awol and leave dummies like me with a massive headache. Although its appreciated, WHY do they not explain in laymen terms and in much more detail? If i knew what i was doing i wouldn't be here! If you are going to write a guide you could at least answer the questions.

    • TOTALLY AGREE they think because they know wot they are on about, every one should. I hate how no one answers questions. they either mustn't no the answer or don't want to tell too much.

      • Dummy and Wayne,

        This is a blog post from 2008, its pretty reasonable that i do not respond to all questions on it, also it has all of the detail that you need to go in search of the further details you wish to find. Its called teaching, not "doing your homework". Also, we all have our own jobs and they take precedence, do remember that this content is available to you for free.

        Now instead of being rude and inconvenient with these posts, how about you go research the PHP manual to find the details? Or if you need answers then wait until other people have time to help you.

  10. This irritates bejebus out of me! 99% of individuals who create content such this seem to go awol and keep idiots like me with a large frustration. Although its valued, WHY do they not describe in laymen conditions and in much more detail? If i realized what i was doing i wouldn't be here! If you are going to create a information you could at least response the concerns.
    http://www.netbean.com.au

  11. What if the writing comes from customer feedback on another website and needs to be covered so it all seems to be in the image? How would I achieve that?
    Removalists in Brisbane

  12. In general, this is a really basic and direct system, and as long as your not hoping to do anything "preposterous" this ought to have the ability to handle it :-) Good Luck!

Comments are closed.