How To Add Text To Images In PHP (Simple Examples)

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");
  • $size = 24; $x = 5; $y = 30; $angle = 0; $quality = 100;
  • $color = imagecolorallocate($img, 255, 255, 255);
  • imagettftext($img, $size, $x, $y, $angle, $color, "PATH/FONT.TTF", "TEXT");
  • imagejpeg($img, "SAVE.JPG", $quality);

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.

 

 

TLDR – QUICK SLIDES

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

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

 

QUICK NOTES

  • Please enable the GD extension extension=gd (or gd2 prior to PHP8) in the php.ini file.
  • In all the scripts, please change the font file $fontFile to your own.
  • Also, make sure that PHP can access the font file.
If you spot a bug, feel free to comment below. I try to answer short 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.

 

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.

 

 

ADD TEXT TO IMAGE

Let us now get into the examples of adding text to an image, it 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.

 

EXAMPLE 1) SIMPLE WRITE TEXT ON IMAGE

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

// (B) WRITE TEXT
$txt = "Hello World";
$fontFile = "C:\Windows\Fonts\arial.ttf"; // CHANGE TO YOUR OWN!
$fontSize = 24;
$fontColor = imagecolorallocate($img, 255, 255, 255);
$posX = 5;
$posY = 24;
$angle = 0;
imagettftext($img, $fontSize, $angle, $posX, $posY, $fontColor, $fontFile, $txt);

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

// (C2) OR SAVE TO A FILE
// $quality = 100; // 0 to 100
// imagejpeg($img, "demo.jpg", $quality);

This is pretty much the “expanded version” of the introduction snippet, as straightforward as can be.

  1. Load the image into an object with imagecreatefromjpeg().
  2. Write text using imagettftext().
  3. Output the image – Directly show it in the browser, save it into a file, save into the database, email it as an attachment, do whatever is required.

 

 

EXAMPLE 2) CENTER TEXT IN IMAGE

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

// (B) TEXT & FONT SETTINGS
$txt = "Hello World";
$fontFile = "C:\Windows\Fonts\arial.ttf"; // CHANGE TO YOUR OWN!
$fontSize = 24;
$fontColor = imagecolorallocate($img, 255, 255, 255);
$angle = 0;

// (C) CALCULATE TEXT BOX POSITION
// (C1) GET IMAGE DIMENSIONS
$iWidth = imagesx($img);
$iHeight = imagesy($img);

// (C2) GET TEXT BOX DIMENSIONS
$tSize = imagettfbbox($fontSize, $angle, $fontFile, $txt);
$tWidth = max([$tSize[2], $tSize[4]]) - min([$tSize[0], $tSize[6]]);
$tHeight = max([$tSize[5], $tSize[7]]) - min([$tSize[1], $tSize[3]]);

// (C3) CENTER THE TEXT BLOCK
$centerX = ceil(($iWidth - $tWidth) / 2);
$centerX = $centerX<0 ? 0 : $centerX;
$centerY = ceil(($iHeight - $tHeight) / 2);
$centerY = $centerY<0 ? 0 : $centerY;

// (D) DRAW TEXT ON IMAGE
imagettftext($img, $fontSize, $angle, $centerX, $centerY, $fontColor, $fontFile, $txt);
 
// (E) OUTPUT IMAGE
header("Content-type: image/jpeg");
imagejpeg($img);
imagedestroy($img);

Yikes! This looks crazy, but the main bulk of this script is calculating the position of the text box. If you want to be a happy person, just skip and use this as-it-is… If not, here’s how the calculations work:

(C1) Self-explanatory. Get the image width with imagesx() and height with imagesy().

(C2) To calculate the dimensions of the text box, we have to use imagettfbbox(). This returns an array with 8 numbers, which are the coordinates of the text box.

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
  • For the width of the text box, we take the right-most point (2 or 4) minus the left-most point (0 or 6).
  • For the height of the text box, we take the top-most point (5 or 7) minus the bottom-most point (1 or 3).

(C3) Lastly, we can calculate the center X and Y positions.

  • Center X = (width of image – width of text box) / 2.
  • Center Y = (height of image – height of text box) / 2.

 

 

EXAMPLE 3) NON-ENGLISH UTF-8 ENCODING

3-utf-8.php
<?php
// (B) UTF-8 TEXT
// https://stackoverflow.com/questions/9458317/working-with-gd-imagettftext-and-utf-8-characters
$txt = "世界你好";
$txt = mb_convert_encoding($txt, "HTML-ENTITIES", "UTF-8");
$txt = preg_replace('~^(&([a-zA-Z0-9]);)~', htmlentities('${1}'), $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.

 

 

EXTRA 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.

 

ADDING TEXT TO PICTURES IN FOLDER

<?php
$files = glob("FOLDER/*.{jpg,jpeg}", GLOB_BRACE);
foreach ($files as $f) {
  $img = imagecreatefromjpeg($f);
  // SAME AS ABOVE - WRITE TEXT TO IMAGE
}

Just get all the images in the folder and loop through all of them.

 

FONT COPYRIGHT

You can specify which font to use, but please do not go on a download frenzy and start using every font 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 get bitten by the law monster if you make money off edited images… Always check the usage license of the “free fonts”.

 

CENTER PARAGRAPH ON IMAGE & AUTO LINE BREAK

All I can say is – Very complicated, good luck. The best place to start is to study and modify the above “center text on image” example.
  • Calculate the dimensions of the “single line text box” and image.
  • Determine how many lines are required to fit the paragraph into the image. That is, break the text into multiple text boxes. Quick pseudo-code:
    • $numlines = ceil(WIDTH OF TEXTBOX / (WIDTH OF IMAGE * 70%));
    • if (HEIGHT OF LINES > HEIGHT OF IMAGE) { ERROR - CANNOT FIT }
    • $lines = [FIND SOME SMART WAY, TO BREAK TEXT, INTO MULTIPLE LINES];
  • Brutal X and Y calculations to position the text boxes.

 

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!

23 thoughts on “How To Add Text To Images In PHP (Simple Examples)”

  1. How can we center a paragraph ? ( when a text arive to the end of the image it will automaticly return to the next ligne and cnter it self:
    example :
    —————————
    —————————
    ———-

  2. Hello sir
    Question : Text On Image php
    How can I add Download link or Download button for Download image with text 100% results
    I hope you reply to me as soon as possible

Leave a Comment

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