Write Multi-line Text On Image With PHP GD

Welcome to a quick tutorial on how to write multiple lines text with PHP GD. So you have probably messed with GD to write some text, only to realize that there is no way to “automatically break into multiple lines”.

At the time of writing, the only way to write multiple lines text with PHP GD is to manually call imagettftext() many times to write text at different positions.

Yes, it’s a real pain. So here’s a quick example of how I “automated” the line breaks – Read on!

 

 

TABLE OF CONTENTS

 

PHP GD WRITE MULTIPLE LINES

All right, let us now get into the example of writing multiple lines text with PHP GD.

 

PART 1) TEXT & FONT SETTINGS

multi-lines.php
// (A) SETTINGS
// (A1) FONT & TEXT SETTINGS
$font = "C:/Windows/Fonts/lucon.ttf"; // CHANGE TO YOUR OWN!
$fontSize = 24;
$fontColor = [0, 0, 0];
$txt = "TAKE A BREAK. DRINK A BUBBLE TEA!";
$maxChar = 13; // max characters per line
$maxLines = 5; // max lines
$offsetX = 3; // "character spacing offset"
$offsetY = 10; // "line height offset"

First, we begin with a whole bunch of settings. Let’s run through them quickly:

  • $font $fontSize $fontColor $txt Don’t think these need any explanation, but I will recommend using monospace fonts. They are much more “predictable” and you can better plan the “max allowed text space on the image”.
  • $maxChar Maximum number of characters per line. In this example, $txt will break into 4 lines.
  • $maxLines If the “broken into lines” $txt has more lines than this, don’t generate the image… It will end up looking funky.
  • $offsetX “Letter spacing”. Yes, GD does not have a native function to control the space between each character, we have to manually set the spacing.
  • $offsetY “Line height”. Again, GD does not have a native function to control the “line spacing”.

 

 

PART 2) DRAW SETTINGS

multi-lines.php
// (A2) DRAW SETTINGS
$angle = 0;        // if you want slanted text
$x = 30; $y = 100; // starting position
$source = "demo.png";
$target = "written.png";

  • $angle Leave this as 0, unless you want slanted text.
  • $x $y The starting position of the first character.
  • $source $target Source image (above), and where to save the processed image.

 

PART 3) BREAK TEXT INTO LINES

multi-lines.php
// (B) AUTO-BREAK TEXT INTO LINES
$tmpX = explode(" ", $txt);
$tmpY = "";
$lines = [];
foreach ($tmpX as $word) {
  if ($tmpY=="") { $tmpY .= $word; }
  else {
    if (strlen("$tmpY $word") <= $maxChar) { $tmpY = "$tmpY $word"; }
    else {
      $lines[] = $tmpY;
      $tmpY = $word;
    }
  }
}
$lines[] = $tmpY;
if (count($lines)>$maxLines) { exit("'$txt' is too long!"); }

Not going to explain this line-by-line (pun intended), but it essentially breaks $txt into an array $lines; Following the rule that only $maxChars characters are allowed per line, and up to $maxLines lines are allowed.

P.S. In this example, $txt will break down into $lines = ["TAKE A BREAK.", "IT'S TIME TO", "DRINK A", "BUBBLE TEA"]

 

 

PART 4) DRAW LINES ONTO IMAGE

multi-lines.php
// (C) DRAW LINES ONTO IMAGE
// CREDITS : https://stackoverflow.com/questions/6926613/php-imagettftext-letter-spacing
$img = imagecreatefrompng($source);
$color = imagecolorallocate($img, ...$fontColor);
foreach ($lines as $line) {
  $tmpX = $x;
  for ($j=0; $j<strlen($line); $j++) {
    $bbox = imagettftext($img, $fontSize, $angle, $tmpX, $y, $color, $font, $line[$j]);
    $tmpX += $offsetX + ($bbox[2] - $bbox[0]);
  }
  $y += $fontSize + $offsetY;
}

Now that we have broken $txt into $lines, we do the very obvious thing – Loop through $lines and draw it line-by-line. What is happening here:

  • foreach ($lines as $line) { DRAW LINE; $y += $fontSize + $offsetY; }
  • Yes, that entire for ($j...) part is literally drawing character by character of each line. Because there is no way to define “letter-spacing”, we have to do it manually. Credits to this post on StackOverflow.

 

PART 5) SAVE PROCESSED IMAGE

multi-lines.php
// (D) SAVE COMPLETE IMAGE
imagepng($img, $target);
echo "OK";

Lastly, just save the processed image. The end. Thankfully.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

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