Adding text to images in real time with PHP

  • PHP
  • February 12, 2008

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 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 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);
comments powered by Disqus

Related Posts

2007 e Férias!

2007 e Férias!

  • December 30, 2006

2006 esta no final, 2007 esta vindo. Muitos blogs fizeram previsões e refletiram sobre o ano que passou, mas eu não vou entrar muito nisso.

Read More
AJAXOnline.com.br

AJAXOnline.com.br

  • September 12, 2006

Na semana passada a internet brasileira passou a contar com mais um portal, o AjaxOnline.

Read More
Cantos arredondados no Ruby on Rails - Um estudo de layouts

Cantos arredondados no Ruby on Rails - Um estudo de layouts

  • August 28, 2008

Estreiando esta nova sessão do meu blog, dedicada ao Ruby on Rails, decidi que ao invés de começa nos principios do RoR (o Nando Viera do Simples Ideias já fez isso bem o bastante) vou iniciar com umas das primeiras peças que criei que podem ser facilmente compartilhadas para que usem em seus sistemas.

Encontrei algumas soluções para cantos arredondados na web, mas eu queria utilizar a solução CurvyCorners que havia encontrado e achado interessante. Eu podia ter simplesmente adicionado o código todo de uma vez e ignorado qualquer coisa, mas decidi seguir a regra DRY (don’t repeat yourself) e comecei a procurar uma solucão para poder utilizar esse código diversas vezes.

A solução que encontrei é diretamente ligada as novas versões do Rails, a renderização de layouts (ou até a de partials tb deve funcionar). Com essa renderização eu poderia criar um bloco com o conteudo do que iria na div, e passar as variáveis que eu preciso. Aliado a isso usei tecnicas de “content_for” que me permitiram adicionar os parametros necessários no cabeçalho do site, sem ter de voltar lá, ou adicionar o código previamente.

Read More