7

I'm using the GD library for PHP, and using functions like imagestring() and imagestringup() to add text to pictures. I am using the built-in fonts with latin2 encoding. Is there a way, with a given string, to calculate the length (in pixels) of the string?

I want to calculate the length in pixels of the strings because the strings are variable and I want to make sure the string doesn't overflow the area I want to put it in.

Thanks for your help.

trip0d199
  • 228
  • 4
  • 9
  • Duplicate to this question: http://stackoverflow.com/questions/1641756/how-to-determine-the-length-in-pixels-of-a-string-being-rendered-on-a-web-page – Martin Apr 17 '12 at 21:14

2 Answers2

7

imagettfbbox() does that: http://www.php.net/manual/en/function.imagettfbbox.php

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
0

If you want to determine the string length of text, using PHP's Build-In-Fonts (e.g. if you are using imagestring()), you can use:

imagefontwidth()


$text = "Your text here"
$fontSize = 5;

$textLength = imagefontwidth($fontSize) * strlen($text);

If you do not use the Build-In-Fonts, use imagettfbbox(), like mentioned above.

TimoRieth
  • 21
  • 1