How to Add Text to An Image

In order to add text to an image, you need two things: the image and the font.

For our example, we will use an existing image, rather than creating our own. We will also need a “.ttf” font file (of any font type/style that you want) uploaded to the server that your script will be running from. (You can download fonts at websites such as Search Free Fonts.)

Three functions are used to create an image from an existing image, so that it can be used/edited. These functions are imagecreatefromgif(), imagecreatefromjpeg() and imagecreatefrompng(). You simply choose which function to use based on your image file type.

The imagettftext() function will be used to actually write the text to the image. The syntax is: imagettftext(resource $image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text)

Most of the imagettftext() function’s parameters are self-explanatory, but let’s review each on briefly.

  • Image = Identifies the Image to Add Text To
  • Size = Specifies Font Size, Usually Measured in Pixels
  • Angle = Degree/Angle Text Should be Printed, With 0 Being Left-to-Right “Normal” Text
  • X = Coordinate (From Left) Indicating Beginning Location of Text
  • Y = Coordinate (From Top) Indicating Beginning Location of Text
  • Color = Color of Text, Usually Already Stored In Variable Using imagecolorallocate() Function
  • Font File = Path to the TrueType “.ttf” Font File
  • Text = String of Text to Be Printed On Image (UTF-8 Encoding)

Now let’s go over the basic outline of the steps that we need to perform:

  • Set the Content Type
  • Create Image From Existing File
  • Allocate A Color For The Text
  • Set Path to Font File
  • Set Text to Be Printed On Image
  • Print Text On Image
  • Send Image to Browser
  • Clear Memory

From here, the code should be relatively simple.

<?php
//Set the Content Type
header('Content-type: image/jpeg');

// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('sunset.jpg');

// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 255, 255, 255);

// Set Path to Font File
$font_path = 'font.TTF';

// Set Text to Be Printed On Image
$text = "This is a sunset!";

// Print Text On Image
imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

// Send Image to Browser
imagejpeg($jpg_image);

// Clear Memory
imagedestroy($jpg_image);
?>

 

Summary:

Function Description
imagecreatefromgif() Creates a New Image From GIF File or URL
imagecreatefromjpeg() Creates a New Image From JPG File or URL
imagecreatefrompng() Creates a New Image From PNG File or URL
imagettftext() Write Text to An Image Using TrueType Fonts

 

Comments