Helping ordinary people create extraordinary websites!

Adding Custom Text to an Image Using PHP

By Darren W. Hedlund
2005-06-21

Adding Custom Text to an Image

This little script will show you how to add a custom text to an image loaded onto your page.

Uisng the PHP_GD function called ImageCreateFromjpeg we will add a custom text to an already existing image file.

This is nice when you want to add in custom text copy right noice but do not want to always have to do that with each file.

To start lets setup the pages information:


<?
header ("Content-type: image/pjpeg");
$string = "Microcyb Rules!!!";                                             
$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, the next part of the code will call the image file, set the text color, get the images deminsions, and figure on where to place the text.


$im = ImageCreateFromjpeg("./PLACE_IMAGE_NAME_HERE.jpg");
$x=imagesx($im)-$width ;
$y=imagesy($im)-$height;
$background_color = imagecolorallocate ($im, 255, 255, 255); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
imagestring ($im, $font, $x, $y,  $string, $text_color);

Finally we produce the new image to be seen.


imagejpeg ($im);

Here is the complete code:


<?
header ("Content-type: image/pjpeg");
$string = "This is sooo cool it works!!!";                                             
$font  = 4;
$width  = ImageFontWidth($font)* strlen($string) ;
$height = ImageFontHeight($font) ;

$im = ImageCreateFromjpeg("./PLACE_IMAGE_NAME_HERE.jpg");
$x=imagesx($im)-$width ;
$y=imagesy($im)-$height;
$background_color = imagecolorallocate ($im, 255, 255, 255); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
imagestring ($im, $font, $x, $y,  $string, $text_color);

imagejpeg ($im);
?>




Tutorial pages:
  • Adding Custom Text to an Image

 1 Votes

You might also want to check these out:


Leave a Comment on "Adding Custom Text to an Image Using PHP"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS