How To Add Text To Images In PHP – Simple Example

Welcome to a tutorial on how to add text to images in PHP. Need to add a watermark or copyright message on uploaded images on a PHP server?

To add text to an image in PHP, we can use the GD extension.

  • $img = imagecreatefromjpeg("IMG.JPG");
  • $white = imagecolorallocate($img, 255, 255, 255);
  • $font = "C:\Windows\Fonts\arial.ttf";
  • imagettftext($img, 24, 0, 5, 24, $white, $font, "TEXT");
  • imagejpeg($img, "SAVE.JPG", 100);

It’s that simple. But let us walk through more examples, along with a simple tip to center the text on the image – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything. Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Text on Image Centering Text
Useful Bits & Links Tutorial Video The End

 

 

DOWNLOAD & NOTES

First, here is the download link to all the example source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code in a zip file – I have released it under the MIT License, so feel free to build on top of it if you want to.

 

QUICK NOTES

  • Please enable the GD extension extension=gd (or gd2 prior to PHP8) in the php.ini file.
  • Access 1-basic.php in your browser for the simple example, 2-center.php for the centered text example.
  • Please do take extra care on the path to the font $font = "C:\Windows\Fonts\arial.ttf", and make sure that PHP can properly access it.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

ADD TEXT TO IMAGE

Adding text to an image is actually very straightforward in PHP. We just need to load it as a new image object in PHP, add some text on top of it, then save it.

 

THE SCRIPT

1-basic.php
<?php
// (A) OPEN IMAGE
$img = imagecreatefromjpeg("balloon.jpg");

// (B) WRITE TEXT
$white = imagecolorallocate($img, 255, 255, 255);
$txt = "Hello World";
$font = "C:\Windows\Fonts\arial.ttf"; 
imagettftext($img, 24, 0, 5, 24, $white, $font, $txt);

// (C) OUTPUT IMAGE
header("Content-type: image/jpeg");
imagejpeg($img);
imagedestroy($img);

// OR SAVE TO A FILE
// THE LAST PARAMETER IS THE QUALITY FROM 0 to 100
// imagejpeg($img, "test.jpg", 100);

 

 

HOW IT WORKS

That’s it, adding text to an image is that simple. But just what the heck are all those numbers and functions used to generate the image? There are 5 main functions that you should know here:

  • imagecreatefromjpeg(FILE) will load your specified jpg file as a new image object.
  • imagecolorallocate(IMAGE, RED, GREEN, BLUE) Allocates a color to be used for drawing on the image.
  • imagettftext(IMAGE, FONT SIZE, TILT ANGLE, X, Y, COLOR, FONT, TEXT) Draws your specified text on the specified image.
  • imagejpeg(IMAGE, FILE NAME, QUALITY) Renders and output a given image object.
  • imagedestroy(IMAGE) Destroys a given image object and forces a garbage collection.

 

 

CENTERING TEXT ON IMAGE

Adding text to an image is easy, but what if we want to center the text on the image? Sadly, it is very Mathematical when it comes to calculating where to put the text…

 

THE SCRIPT

2-center.php
<?php
// (A) OPEN IMAGE
$img = imagecreatefromjpeg("balloon.jpg");

// (B) WRITE TEXT
$white = imagecolorallocate($img, 255, 255, 255);
$txt = "Hello World";
$font = "C:\Windows\Fonts\arial.ttf"; 

// THE IMAGE SIZE
$width = imagesx($img);
$height = imagesy($img);

// THE TEXT SIZE
$text_size = imagettfbbox(24, 0, $font, $txt);
$text_width = max([$text_size[2], $text_size[4]]) - min([$text_size[0], $text_size[6]]);
$text_height = max([$text_size[5], $text_size[7]]) - min([$text_size[1], $text_size[3]]);

// CENTERING THE TEXT BLOCK
$centerX = CEIL(($width - $text_width) / 2);
$centerX = $centerX<0 ? 0 : $centerX;
$centerY = CEIL(($height - $text_height) / 2);
$centerY = $centerY<0 ? 0 : $centerY;
imagettftext($img, 24, 0, $centerX, $centerY, $white, $font, $txt);

// (C) OUTPUT IMAGE
header("Content-type: image/jpeg");
imagejpeg($img);
imagedestroy($jpg_image);

 

 

THE MATH BEHIND TEXT CENTERING

Centering a block of text in the middle of the image requires a lot of calculations. If you want to know how it works, read the below section. If not, just be a happy man and use the code as it is. 😆

  • First, we get the width of the image with imagesx() and height with imagesy().
  • Next, we have to calculate the size of the text box… Which is not-so-straightforward.
  • We use imagettfbbox() to get an array containing all the coordinates of the bounding box around the text.

Key Position
0 lower left corner, X position
1 lower left corner, Y position
2 lower right corner, X position
3 lower right corner, Y position
4 upper right corner, X position
5 upper right corner, Y position
6 upper left corner, X position
7 upper left corner, Y position
  • In order to calculate the width and height of the text box, we have to take the furthest points apart from each other.
  • E.g. In the above example, 6 is the left-most point and 2 is the right-most point. So we calculate the width by taking the distance between 6 and 2; The height is the distance between 1 and 5.
  • Finally, we can calculate the coordinates to place the text box right in the middle of the image:
    • X coordinate: (Width of image – width of text box) / 2
    • Y coordinate: (Height of image – height of text box) / 2

 

 

USEFUL BITS & LINKS

That’s it for the scripts. But before we wrap things up, here are a few more nuggets of information that you might be interested in.

 

NON-ENGLISH UTF-8 ENCODING

3-utf-8.php
<?php
// (B) WRITE UTF-8 TEXT
// https://stackoverflow.com/questions/9458317/working-with-gd-imagettftext-and-utf-8-characters
$white = imagecolorallocate($img, 255, 255, 255);
$txt = "世界你好";
$txt = mb_convert_encoding($txt, "HTML-ENTITIES", "UTF-8");
$txt = preg_replace("~^(&([a-zA-Z0-9]);)~", htmlentities('${1}'), $txt);
$font = "C:\Windows\Fonts\simsun.ttc"; 
imagettftext($img, 24, 0, 5, 24, $white, $font, $txt);

If you are working with non-English languages, GD is not exactly the friendliest. But all credits go to this post on StackOverflow – Just use a font for your required language and do a bit of manual UTF-8 encoding.

 

FONT COPYRIGHT

You can specify a font to write onto the images, but please do not go on a download frenzy and start using every font that you find on the Internet. There is a hidden nightmare behind fonts, and it is called copyright. Yes, some fonts are subjected to copyright, and you can potentially get bitten by the law monster if you make money off the edited images… Always check the usage license of the “free fonts” before you use it.

 

REFERENCES & LINKS

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

How To Add Text To Image In PHP (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this short tutorial. I hope it has answered your question on how to add text to an image, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

17 thoughts on “How To Add Text To Images In PHP – Simple Example”

  1. Thank you so so much.. Have been struggling on this more than a week. But still the text is not properly centered on the image. My image dimensions is 720*480. Can u help?

  2. In my case, it is not showing text on image. i checked gd enabled.
    Even i tried by deploying zip folder of basic.php, and remain same problem.

  3. Hello!
    Thank you for this; I made good use of it. 🙂

    I thought I’d save a couple of lines of code though by doing the math this way:

    $x = max(CEIL(($w – $text_width) / 2), 0);
    // obviates $x = $x < 0 ? 0 : $x;
    $y = max(CEIL(($h – $text_height) / 2), 0) +/- $adjustment;
    // obviates $y = $y < 0 ? 0 : $y;

    Also note that I added an adjustment factor to $y 'cause depending on the font, it might not vertically-center properly.

    Cheers!

  4. Hi
    thank you for the code. There is an error on line 12 when I run the code and found “imagedestroy($jpg_image);” .
    I have changed it to “imagedestroy($img);” and now is working correctly.

  5. Hi thank you,
    jsut a segnalation.
    the right code is:

    $centerX = CEIL(($width – $text_width) / 2);
    $centerX = $centerX<0 ? 0 : $centerX;
    $centerY = CEIL($height / 2);
    $centerY = $centerY<0 ? 0 : $centerY;
    imagettftext($img, 24, 0, $centerX, $centerY, $txtColor, $font, $txt);

Leave a Comment

Your email address will not be published. Required fields are marked *