How to Add Text in an Image

November 15, 2007 |  by Anish Blon
d93e9b2d836bf02070f851fa34620cc9 Del.icio.us

This small script describes how to add a custom text to an image loaded onto your page. One of my client wanted to add a copyright notice in her images related to her site. So, I came up with this small PHP script for her.

Adding Text to an Image

Using the PHP GD function called imagecreatefromjpeg, imagecreatefromgif and imagecreatefrompng. We can add a custom text to an already existing image file.
So you have imagecreatefromjpeg for jpeg file, imagecreatefrompng for png file and so on.

< ?php
header("Content-type: image/png");
$string = "copyright: some text";
$font = 4;
$width = imagefontwidth($font)* strlen($string) ;
$height = imagefontheight($font) ;

This will setup the structure of the data being sent to the image file as well as what location to place the text at. In this case we want to place it on the bottom right of the page.

Now, we use imagecreatefrompng to create image from a file, set the text color, get the images dimensions, and figure on where to place the text.

$im = imagecreatefrompng("/path/to/yourimagefile");
$x = imagesx($im) - $width ;
$y = imagesy($im) - $height;
 
$backgroundColor = imagecolorallocate ($im, 255, 255, 255);   //white background
$textColor = imagecolorallocate ($im, 0, 0, 0);   //black text
imagestring ($im, $font, $x, $y,  $string, $textColor);

Finally we produce the new image that will display custom text in an image.

imagepng ($im);
?>

Here is the complete code:

< ?php
header ("Content-type: image/png");
$string = "your text";
// try changing this as well
$font = 4;
$width = imagefontwidth($font) * strlen($string) ;
$height = imagefontheight($font) ;
$im = imagecreatefrompng("/path/to/yourimagefile");
$x = imagesx($im) - $width ;
$y = imagesy($im) - $height;
$backgroundColor = imagecolorallocate ($im, 255, 255, 255);
$textColor = imagecolorallocate ($im, 0, 0,0);
imagestring ($im, $font, $x, $y,  $string, $textColor);
imagepng($im);
?>

You may like to view demo.


4 Comments


  1. it didn’t work.. it only outputs the location of the php file but in image form.

  2. bob the dangerous

    You cannot place any rendering code in this file as it’s returning just an image file.

    No session_start, echo or just plain HTML.

  3. i have a images.i want to add a text to this image.you cant give me a example ?

Trackbacks

  1. Alexsander Akers 

Leave a Reply