Web Development

Adding Custom Text to an Image Using PHP

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:

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.

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:

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);
?>

About the author

Written by Darren W..

Darren Hedlund is a freelance Web developer, writer, and data analyst. Darren has a degree in Computer Information Science and has spent the last 15 years developing application and environments from hand held, windows, web, virtual science, gaming, artificial intelligence and graphics design.

Darren's coding knowledge ranges from C+, Visual Basic, .NET, PHP, JSP, REXX, KIXX, and many others. His graphical and environmental knowledge stems in Macromedia Flash, 3D studio Max, Curious Labs Poser, Adobe Photoshop, and many others. Darren works in many platforms ranging from database, visual design, and, system development.

If you found this post useful you may also want to check these out:

  1. Creating Custom Functions
  2. Creating an Image Gallery with PHP
  3. Text::Autoformat: Smart Text Reformatting with Perl
  4. Drawing a Wavy Image using Pen Tool
  5. Fixed Image Background for a page
  6. How Can I Mount a ISO Image CD?