You are here

15 December 2010
This tutorial shows how you can add text to images with PHP. You can use it to make banners with dynamic content for an example.

Load Image Data From a File:

Source code viewer
  1. $photo = imagecreatefromgif('img.gif');
Programming Language: PHP

Turn Alpha Blending On:

Without ImageAlphaBlending on, the final result won't render correctly.
Source code viewer
  1. imagealphablending($photo, true);
Programming Language: PHP

Set Configuration:

Source code viewer
  1. #font size
  2. $fontsize = 20;
  3. #font file
  4. $font = 'font.ttf';
  5. #font color
  6. $fontcolor = imagecolorallocate($photo, 255, 255, 255);
  7. #font rotation angle
  8. $angle = 0;
  9. #location
  10. $x = 10;
  11. $y = 10;
  12. #text that will be written on the image
  13. $text = 'text';
Programming Language: PHP

Add Text to Image

Source code viewer
  1. imagettftext($photo, $fontsize, $angle, $x, $y, $fontcolor, $font, $text);
Programming Language: PHP

Display the Image

This code displays the image in browser and you can use the url as image. You can also write the image to a file.
Source code viewer
  1. header('Content-Type: image/gif');
  2. imagegif($photo);
Programming Language: PHP