Recently I took on a project where a client needed to generate an image on the fly, with a particular quote and they wanted to scale the text to fit the image on the fly. Which sounded perfectly daunting.
But, I decided to try to tackle the problem anyway.
It turns out there are plenty of tutorials on how to add text to an image with PHP using
annotateImage. But none of them deal with the specific problem of scaling your text to fit in a particular space on the image. Nor do they adequately handle fonts and sizing and text wrapping.
In my searches, I came upon a few pieces that helped me get there, and ultimately resulted in a magic function I’m calling:
Autofitting Text To An Image With PHP
Enough talk. Here’s the guts of the new function:
Now, I know: that looks terrifying. But it isn’t so bad. It just turns out there are quite a few things we need to know to at the outset.
Let’s walk through an example. For this demo, we will simply need an image to write text to and a font. Here are my files:
quote_canvas.png is the image I’m going to write text to.
Cedarville-Cursive.ttf is my font.
And here is test.php:
When I run test.php, a new file appears in the directory:
Which contains my original image, plus the text we wrote to it:
Now, what happens if we reduce the length of our text and run it again? Here’s the output:
You’ll notice the font size increased to the max starting font size we specified in the beginning:
If we conversely increase the amount of text, the font size will decrease:
Putting it Together with WordPress
What if we were in a WordPress context and wanted to create the image, put it in the proper WordPress uploads directory and then set the current post’s featured image to our newly generated image? It would look something like this:
The above code could be easily implemented within an action on
save_post, and could even load the text details from the post attributes or meta.
A Word on Performance
This function should not be run on the fly. You should only use it to generate and save an image.
Calculating the line heights and correct font size is an expensive operation and it would be quite easy for you to take down your site, improperly implemented.