Add Text to Image

This small script describes how to add a custom text to an image into your web page

Adding Text to an Image

We will use PHP GD functions

  • imagecreatefromjpeg
  • imagecreatefromgif
  • 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: programmersbank.com ";
$img_font= 4;
$img_width = imagefontwidth($img_font)* strlen($string) ;
$img_heigh = imagefontheight($img_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("img.jpg");
$x = imagesx($im) - $img_width ;
$y = imagesy($im) - $img_heigh;

$backgroundColor = imagecolorallocate ($im, 255, 255, 255); //white background
$txt_color = imagecolorallocate ($im, 0, 0, 0); //black text
imagestring ($im, $img_font, $x, $y, $string, $txt_color);

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 = "programmersbank.com";
// try changing this as well
$img_font= 4;
$img_width = imagefontwidth($img_font) * strlen($string) ;
$img_heigh = imagefontheight($img_font) ;
$im = imagecreatefrompng("/path/to/yourimagefile");
$x = imagesx($im) - $img_width ;
$y = imagesy($im) - $img_heigh;
$backgroundColor = imagecolorallocate ($im, 255, 255, 255);
$txt_color = imagecolorallocate ($im, 0, 0,0);
imagestring ($im, $img_font, $x, $y, $string, $txt_color);
imagepng($im);
?>

Bookmark This Page

Link Partners