4

I'm using imagettftext() to write dynamic text on an image and I want it to fit my image width.

How can I calculate the font size by the text lenght?

octern
  • 4,825
  • 21
  • 38
Asaf
  • 91
  • 1
  • 1
  • 8
  • You can't calculate the font size by the text length unless it's a monospace font. And there is no good approximation. A string of all W's will take up much more space than a string of all I's. – Brian Warshaw May 21 '12 at 16:57

2 Answers2

12

You can calculate the bounding box of TTF text before outputting it with the imagettfbbox function. Unfortunately there is no direct way of scaling to fit a width, so you'll have to do it yourself.

One way of doing it is to pass the text with a default font size of, say 20, to imagettfbbox and retrieve the width from it. You can then calculate how much smaller or bigger the text should be to fit the size you want by calculating a scale factor:

scale = targetWidth / bboxWidth;

Then draw the text with the proper size:

fontSize = 20 * scale;

using the imagettftext function. Fonts don't scale 100% perfectly this way, but you'll get a very good approximation.

See the documentation of imagettfbox here.

Overv
  • 8,433
  • 2
  • 40
  • 70
  • To make the scale 100% perfect you could do a second pass with font 40 and calculate the scale based of the difference between 20 and 40 font size for the same input string. – Programista Aug 23 '12 at 00:43
-2
while (itsTooBigAccordingToimagettftext() && $fontSize > 0) {
    $fontSize--;
}
goat
  • 31,486
  • 7
  • 73
  • 96
  • 2
    This will result in "Fatal error: Call to undefined function itsTooBigAccordingToimagettftext()". In other words, please give a better explanation of your answer instead of using semi-code :-) – Kapitein Witbaard Aug 15 '14 at 14:53
  • 2
    Stackoverflow is a place where you're supposed to get guidance, not a fully working code. To me that's good guidance, the only error is it should read `itsTooBigAccordingToimagettfbbox()` and not `itsTooBigAccordingToimagettftext()` ;-) – Capsule Apr 15 '15 at 02:07
  • 2
    Warning: Doing *can* cause long delays if you are not careful. – starbeamrainbowlabs Aug 02 '15 at 13:39