How to create multicolor text image on the fly

This tutorial explains how we can create dynamic images with multicolor text in PHP.

We will need GD library and FreeType library to be enabled for this functionality to work.

I have assumed that you already know PHP, and understand how to use it.

Check the example below to see what we want to create.

Amit Singh

Before we start the tutorial, let’s check if GD library support is available on your system or not.

Type phpinfo(); in a php file, and check the output.

phpinfo_gd

You should see something like that you can move forward, else goto php.ini and remove the comment from extension=php_gd2.dll. Now check phpinfo() again to verify that every thing is ok.

Now, let see how we can create dynamic images using PHP.

CODE

Header ("Content-type: image/png");

putenv('GDFONTPATH=' . realpath('.'));
$font = 'nevis.ttf';
$fontSize=20;//in point;

$title1= 'Amit';

$title2= 'Singh';

$str=$title1.'   '.$title2;

$onecharwidth  = imagefontwidth($font)*($fontSize/8);

$totalwidth  = $onecharwidth * strlen($str);

$height = (imagefontheight($font)*($fontSize/8))*2;

$img_handle = imagecreatetruecolor($totalwidth, $height);

$white = imagecolorallocate($img_handle, 255, 255, 255);

imagefill($img_handle, 0, 0, $white);

$black = imagecolorallocate ($img_handle, 0, 0, 0);

$gray = imagecolorallocate ($img_handle, 100, 100, 100);

imagettftext($img_handle, 20, 0, 10, 20, $black, $font, $title1);

$posarr=imagettfbbox(20, 0,$font, $title1);

imagettftext($img_handle, 20, 0, $posarr[2]+$onecharwidth, 20, $gray, $font, $title2);

imagepng ($img_handle);

imagedestroy ($img_handle);

Explanation

No need to fear, I am about to explain what each line of code is doing, so that you can bend it to your own needs.

 Header ("Content-type: image/png");

This line tells browser that whatever we are outputting needs to be treated like image.

putenv('GDFONTPATH=' . realpath('.'));
$font = 'nevis.ttf';$fontSize=20;

This line tells the php to set the search path for the folder to be current directory where this file is stored. While the $font variable stores the name of the font, notice the extension ‘.ttf’. Download Nevis font ,$fontSize is size of the text in points, i.e. 20pt. If safe mode is enabled you might not be able to set the environment variable.

$title1= 'Amit';
$title2= 'Singh';
$str=$title1.'   '.$title2;

These lines are self evident, the reason for $str is to get the complete sting so that we can calculate size of the image required to show the text.

$onecharwidth  = imagefontwidth($font)*($fontSize/8);
$totalwidth  = $onecharwidth * strlen($str);
$height = (imagefontheight($font)*($fontSize/8))*2;

This block of code is used for calculation of font size and and height etc. imagefontwidth() function returns the width of one character for specified font at 8pt size in pixels, Similarly imagefontheight() function returns the height of the single character in pixels.

Now from this information we will need to calculate the size of single character for actual font size that we are going to use, in our case it is 20pt, hence the calculation ($fontSize/8). Once we calculate width of single character, we will then calculate the width of whole string that we need to display and store it in $totalwidth.

$img_handle = imagecreatetruecolor($totalwidth, $height);
$white = imagecolorallocate($img_handle, 255, 255, 255);

imagefill($img_handle, 0, 0, $white);

In this block we create a black image of the size specified, and the fill it with white color so that we have white background.

imagecreatetruecolor() returns the image with black background, we then fill the background with white color using imagefill() function. Each color that we will be using needs to be created using the call to imagecolorallocate() function.

$black = imagecolorallocate ($img_handle, 0, 0, 0);$gray = imagecolorallocate ($img_handle, 100, 100, 100);

As explained above, I just created two more colors to use with the text, black and gray.

imagettftext($img_handle, $fontSize, 0, 10, 20, $black, $font, $title1);
$posarr=imagettfbbox($fontSize, 0,$font, $title1);
imagettftext($img_handle, $fontSize, 0, $posarr[2]+$onecharwidth, 20, $gray, $font, $title2);

In this block we actually write the text on the image. I have used imagettftex() function to write the text to image in the font specified by $font. Since their are two words we needed to know the pixels, from where we could write the next word. I used imagettfbox() to get the dimension of the box that surrounds the first word, then we added the pixels need for single character(space) and then we wrote second word as well.

Once done our image is now ready to be sent to user.

imagepng ($img_handle);
imagedestroy ($img_handle);

We are sending the raw image stream to the browser, by calling imagepng() function, and then we destroy the image and free the server memory.

That it we are done, we have created an dynamic image with multicolor text on it. Now we need to use this image, so

<img src=”image.php”>

Simple isn’t it? Well to make it even simpler I have wrapped all this in a general function that you download and use it.

Just pass the data array and it will give you the image. Something like this

Amit Kumar Singh

Download [download#7#nohits].
If you have any questions, doubts or suggestions just leave a comment below.

7 thoughts on “How to create multicolor text image on the fly

  1. hi this is kesavan…
    when i save this image..it saved as a ‘.php’ file..
    how can i save the image as a ‘.png’ file?

  2. hi this is kesavan…
    when i save this image..it saved as a ‘.php’ file..
    how can i save the image as a ‘.png’ file?

  3. Thank you very much. nice tut.

    How about filling a text with a pattern or an image instead ?

    Is that possible ? can you afford that code for us ?

  4. Hi,

    Deployment as:
    makes whole thing quite unusable/static/worthless, as all vars must be included within img.php file and any var injection is questionable.
    If you try to deploy it as require(), you will get into “header” problems.

    Up to now I did not find any way to go around it … do you know of such way?

    Jeff

  5. I got something, which may make it dynamic.

    Simple GET can be used here eg.: <img src=”image.php?data=any_data_here”>

    Jeff

Comments are closed.