Adding Custom Text to an Image Using PHP
by Darren HedlundMicrocyb.com
Monday, 7th November 2005
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.
$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.
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);
?>
Options:
Printer Friendly
Email Friend
Darren Hedlund is a freelance Web developer, writer, and data analyst. Darren has a graduate 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.
