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!

ⓘ I have included a zip file with all the 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.

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

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

 

QUICK NOTES

  • Edit multi-lines.php, change $font to your own.
  • Just run multi-lines.php in the browser or command line – It will write text on demo.webp, and save it to written.webp.
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, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

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 = [255, 255, 255];
$txt = "TAKE A BREAK. IT'S TIME TO DRINK A BUBBLE TEA!";
$maxChar = 13; // max characters per line
$maxLines = 5; // max lines
$offsetX = 3;  // "character spacing offset"
$offsetY = 20; // "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
$quality = 90;     // image quality
$source = "demo.webp";
$target = "written.webp";

  • $angle Leave this as 0, unless you want slanted text.
  • $x $y The starting position of the first character.
  • $quality Output image quality, 0 to 100.
  • $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 = imagecreatefromwebp($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
imagewebp($img, $target, $quality);
echo "OK";

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

 

 

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 *