Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » php » Text On Image

Text On Image

Learn how to display text on an image using the GD Library in PHP.

This tutorial REQUIRES the GD Library to be installed in order to work.

Here is the code.

$image = ImageCreateFromPNG("base.png");
$color = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$colorShadow = imagecolorallocate($image, 0x66, 0x66, 0x66);
$font = 'arial.ttf';
$fontSize = "10";
$fontRotation = "0";
$str = "Example of GD in PHP.    Date: " . date("m-j-Y  g:i:s (a)");

/* Shadow */
ImageTTFText($image, $fontSize, $fontRotation, 7, 22, $colorShadow, $font, $str);

/* Top Level */
ImageTTFText($image, $fontSize, $fontRotation, 5, 20, $color, $font, $str);

header("Content-Type: image/PNG");
ImagePng ($image);


$image is the background that the string is applied to
$color is the applied text's color 
$colorShadow is the color of the drop shadow
$font is the font loaded to create the image
$fontSize is the size of the font "imagine that" :)
$fontRotation is the amount the text will be rotated [default = 0]
$str is the text that is printed on the image


Here is an explanation on what each of the variables are.

$image = ImageCreateFromPNG("base.png");

This is the php function to create a PNG using a starter image. For this example the starter image is named "base.png"

// '0x' is placed before the value for a hex value otherwise you give an "RGB" value
$color = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$colorShadow = imagecolorallocate($image, 0x66, 0x66, 0x66);

This line is used to set the foreground & shadow of the text that we will render. The first parameter is calling the base image. The next 3 are the color values of the text and shadow. (ex: #333333 is changed to 0x33,0x33,0x33)

$font = 'arial.ttf';
$fontSize = "10";
$fontRotation = "0";

$font is the font file loaded to draw the text. You must upload that font file to your server in order for this example to work. $fontSize is the size of the rendered text. $fontRotation is the amount of rotation applied to the text.

$str = "Example of GD in PHP.    Date: " . date("m-j-Y  g:i:s (a)");

$str is the string(text) we will render to the PNG. For added coolness we will render the date and time.

/* Shadow */
ImageTTFText($image, $fontSize, $fontRotation, 7, 22, $colorShadow, $font, $str);

/* Top Level */
ImageTTFText($image, $fontSize, $fontRotation, 5, 20, $color, $font, $str);

'Top level' & 'Shadow' have most of the same parameters, the Difference is placement on the image. The first param is the image that is edited, the second param is the font size, the third param is the rotation of the text, the fourth param is the distance from the left side, the fifth param is the distance from the top

header("Content-Type: image/PNG");

This sends a command to the browser that says this filetype is PNG. This is set so the browser doesn't think it is a page.

ImagePng ($image);

This sends the image to the browser which sets the browser to display the new generated PNG.


After the image is displayed 'destroy' it to clear the buffer. This used a small piece of the buffer but every bit adds up.

That is the end of the tutorial. Now you should have a better understanding how to add text to an image.

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Text On Image

 doolally  Sun Dec 17, 2006 10:32 am  
Thank you for this tutorial

Can other image formats be used, i.e. jpeg, gif?
 Matthew  Tue Dec 19, 2006 3:51 am  
Yes, you can use other image formats. You would substitute the "PNG" for gif,jpg. At the moment I think those are the only formats allowed.
 doolally  Tue Dec 19, 2006 12:34 pm  
 doolally  Fri Dec 22, 2006 5:30 am  
Me again with another question,

How do you call the image from another page?
 Matthew  Fri Dec 22, 2006 5:38 am  
To return an image you would simply call the PHP page in an IMG tag. PHP will automagically send back the image data and HTML will render it.
 doolally  Fri Dec 22, 2006 6:01 am  
Thanks again
 Dan Lev Designs & Photogr  Tue Jan 2, 2007 9:06 pm  
Thank you so much! This was very helpful!
 Janusz Jasinski  Thu Jan 18, 2007 1:15 am  
How do I restrict the text within a certain area?

Let's say I have a 400x400 box and I have lots of text, at the moment, it will go off the end...

... I need iot to stay withing the box (wrap?)


P.S. Cool page!
 Andy  Mon Jan 29, 2007 11:20 am  
Can anybody help me - i've used this, and i get "Warning: Cannot modify header information - headers already sent by (output started at /home/sites/ in /home/sites/ on line 15
 Andy  Mon Jan 29, 2007 11:22 am  
I should probably have said that the above is in functions.php and called from test.php.
There is a load of what appears to be rubbish printed after it too, however i suspect it's the image is some random text based form...
 Xavier  Tue Mar 13, 2007 1:28 am  
Hello I have the same problem like Andy.
I put the code in a that I call using a require_once.
Can you explain how to display the image if we want to call a function that does the code in stead of just have an image on a blank page?
Thanks a lot
 mkeefe  Tue Mar 13, 2007 3:19 am  
Make sure the call to this code is before the display of any HTML, which would cause that "Headers Sent" error.
 Cheeseweasel  Tue May 15, 2007 9:02 am  
Fatal error: Call to undefined function: imagecreatefrompng() in \\nas31ent\domains\s\\user\htdocs\php\dynamic\index.php on line 2
 mkeefe  Tue May 15, 2007 9:21 am  
That means you don't have the GD library installed, for more information check out the site. Hope that helps.
 Jason  Sat Jun 23, 2007 1:06 pm  
Is there a way to asdd a style to it? like make it bold?
 Matthew  Sat Jun 23, 2007 1:57 pm  
In order to make it bold or have styles in it you would need the fonts.
 Jason  Sat Jun 23, 2007 2:02 pm  
that did it :) thank you
 IONT  Wed Jun 27, 2007 12:49 pm  
How do i restrict the length of text before it goes to another line?
 mkeefe  Wed Jun 27, 2007 1:43 pm  
That would depend on the font and spacing but you basically would count the characters with strlen(). So it will take some trial and error as it really does depend on the font.
 adam  Thu Jun 28, 2007 9:23 pm  
when I try to imagepng on an image i created with ImageCreateFromPNG it outputs strange encoded looking text instead of an image. any advice would be helpful
 adam  Thu Jun 28, 2007 9:28 pm  
i figured an example may be helpful:

�PNG  ��� IHDR�����
#65533;�ꞙ.�\N�t� 8����DDDT�8�&
533;��CU�,o�{�5"��@'y纪 �M��";�}+���&
#65533;Ƞ-��zD�~�΅ if�&#
65533;�83 �ٛ��h)��,��P&
�Z�} �DD�Z��9����q��&#

is the first few lines of a picture that should be this:
 mkeefe  Thu Jun 28, 2007 10:19 pm  
Are you setting the headers to PNG? and make sure you are not printing or echoing any other text before or after it.
 adam  Fri Jun 29, 2007 9:33 am  
i have header("Content-type: image/x-png"); in my header section and i have echo lines before it but when i remove them the pic is still that text.
 mkeefe  Fri Jun 29, 2007 10:12 am  
Try this header:

header("Content-Type: image/PNG");
 adam  Fri Jun 29, 2007 10:36 am  
it was the header in the wrong place. thanks all.
 Hmm  Wed Aug 22, 2007 10:08 am  
How can i add more lines instead of that with the date?
 to Hmm!  Mon Feb 25, 2008 2:08 am  
to add more lines, do this:

$str = "LINE1 n LINE2 n LINE3";

/and so on... just add " n " after each line
 web designer  Sun Mar 23, 2008 6:33 pm  
is there's a way to generate the image within the page? There's an input box and then when user inputted a text and clicked the preview button the image will generate within the page..
 web designer  Sun Mar 23, 2008 6:47 pm  
I created a function and then called it before the HTML tags.

my error is "Warning: Cannot modify header information - headers already sent by......"

Im trying to load the image within the page..

What am i doing wrong?

 mkeefe  Sun Mar 23, 2008 8:36 pm  
You need to place the PHP before any HTML code, or use ob_start() to store the output and then use ob_end_flush() to display the contents.

You could also use some Ajax-type system that loaded the image with the new information. It really depends on the application.
 Boris   Tue Jun 10, 2008 11:52 am  
This script has helped me a lot! Opens a whole new world for me.

One thing I don't understand. How do you post a variable to this script? Right now I refer to the generate.php file within in image tag but if I add a variable it is just ignored: generate.php?count=1526
gives me nothing...
 mkeefe  Tue Jun 10, 2008 12:00 pm  
@Boris, You should be able to pass variables using the super-global $_GET array.

Such as: $_GET['count'];

Hope that helps,

 Pario  Sun Jun 22, 2008 11:44 am  
Geras dalykas :) Dekui
 Help  Fri Jul 25, 2008 12:46 pm  
I know that GD is installed, I used the same script as you but used my own image yet this script doesn't output anything :-/ Please Help
 mkeefe  Sun Jul 27, 2008 5:53 pm  
@Help - I recommend you enable error_reporting and display_errors in your PHP configuration file (php.ini).
 Victor Ocampo  Sun Aug 17, 2008 4:20 pm  
Hi dude, thanks alot, it was easier than i tough, how ever, in some images i see some bad quality, i had same problem with image resample, but i fixed using different function which uses more CPU, but sometimes is required. What could i switch in here for a better quality result? THANKS
 mkeefe  Sun Aug 17, 2008 7:41 pm  
@Victor - Are the files your editing saved as progressive? I have seen some worse quality when the starting file is progressive JPEG.
 Matt  Tue Sep 16, 2008 2:23 pm  
Hi, I got this working correctly. I just have one question. How can I set a margin around the text. Eg I want a 5px margin from the edge of the image.
 matt  Tue Sep 16, 2008 3:25 pm  
One other thing I forgot. How or is it possible to have line feeds to space the text? I tried the suggestion above but it just prints whatever I type.
 mkeefe  Tue Sep 16, 2008 6:43 pm  
@matt - You would have to calculate that based on the width of the text, and the font. I am not aware of default padding options. Again, for the line feed option, you would need to space the text based on width and this time include height.

Maybe PHP will have some better measurement and spacing tools, like Flash or other drawing apps, but there aren't any official tools that I am aware of.
 Chris Dev  Tue Nov 4, 2008 1:27 am  
How can I add HTML tag into image suppose I would Like Chris Dev Or

Chris Dev


How come I do that?
 Guest  Tue Nov 4, 2008 1:30 am  
How can I add HTML tag into image suppose I would <b>Chris Dev</b> Or
<H1>Chris Dev</h1>

Also I need to enter <br> into image txt...

How come I do that?
 Shane  Tue Dec 2, 2008 11:04 am  
Example works after defining the proper font location.
If you have errors and get garbled text after the warnings, it may be because the font file cannot be located.

You can try adding

putenv('GDFONTPATH=' . realpath('.'));

or adding the full path to the font, ie on windows
$font = 'C:\xampp\htdocs\arial.ttf';

I don't think you can use your css/html, gd parses the entry as text. (might be wrong, not a guru)

To create a new line/line feeds, you can use
"n" without the quotes.

 John Sujith  Fri Dec 5, 2008 9:54 pm  
hi guys ,
well and i have one request that is ,is there any possible to generate image from dive content[text] like following link show that image , i need a image which only from dive content ,plz let me know if any body have idea ! by PHP ,GD
advance thanks
Image url :

best regards,
 mkeefe  Mon Dec 8, 2008 10:47 am  
@John - I don't understand the question. Do you mean display a paragraph of text as an image?
 Alexis  Thu May 14, 2009 2:06 am  
Hi thanks for the tutorial, how would you change the "$str" value dyamically from a form? I want to have a forum which users fill in, then it loads the image with the text on.

Any help would be most greatful. :-)
 mkeefe  Mon May 25, 2009 12:19 pm  
@Alexis - I think you want to look into $_POST data for processing form contents.
 Julie  Wed May 27, 2009 1:22 pm  
Is there any chance you could post the code required to call it from the HTML page?
I can get the HTML page to show the image, but the text isn't showing up for me.
 Jamie Hutber  Sat Oct 31, 2009 12:04 pm  
Just wanted to say thanks for the quality guide. Its written so you can't really have any errors :)

CHeers Jamie
 Jamie Hutber  Sat Oct 31, 2009 12:05 pm  
Thats what i use.
 Darragh Nugent  Sun Nov 8, 2009 2:30 am  
For my final year project i have a search feature written in PHP and it is linked to a My SQL database which displays a map written in text on my website when searched. What i have to do is have the map currently written in text displayed as a series of images and icons when searched in the database. I was wondering could you please advise me of a possible way to do this!

Darragh Nugent
 mkeefe  Wed Nov 11, 2009 4:43 pm  
@Darragh - I am not fully sure what you are asking to build. Do you mean a map, like Google Maps or a sitemap navigation?
 Jacob  Sun Nov 29, 2009 10:04 pm  
I have used the php ImageTTFText function to do image texting.

Now do i assign the create text image to teh Google Icon Image

See below my code:

** image.php **

//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(35,16);

// sets background to Orange 4
$background_orange4 = imagecolorallocate($im,139,37,0);

//Create some color
$white = ImageColorAllocate($im,255,255,255);

// image creation
ImageFilledRectangle($im,1,1,76,76,$white); //text color
ImageFilledRectangle($im,5,5,72,72,$background_orange4); //image shadow color set to scarlet

//Replace path font

//The text to draw

// determine numeric center of image
$size = ImageTTFBBox(7,0,$font,$text);
$X = (35 - (abs($size[2]- $size[0])))/2;
$Y = ((16 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image

// returns completed image to calling script

Header('Content-Type: image/png');




// Temperature.php

//The resultset of temperatures at various points(coordinates)
$query="SELECT temperature,coordinates FROM mytable";


if(!$result) {
echo "

Data Not available.

} else {
$numofrows = mysql_num_rows($result);