1

I have a string with font and i need to find it's width, and then width of each char in this string, I'm using GD lib imagettfbbox for this, but it always gives me different result in the end.

$text="some random text";
$info=imagettfbbox(18,0,'/var/www/html/ARIAL.TTF',$text);
$text_width=$info[2]-$info[0];

$text_width_by_chars=0;
for($i=0;$i<strlen($text); $i++){
    $char=$text[$i];
    $info=imagettfbbox(18,0,'/var/www/html/ARIAL.TTF',$char);
    $char_width=$info[2]-$info[0];
    $text_width_by_chars+=$char_width;
}
echo $text_width.' '.$text_width_by_chars;

It happens to all fonts doesnt metter if $info[0] posetive or negative or 0, the differance is always around strlen($text) but not exactly, i've tried to find out if i can mutiply char width to some multiplier but it doesn't work, it's always around 0.91. Why does it happen? And how can i prevent this so in the end $text_width and $text_width_by_chars become equal?

tttaaabbb
  • 407
  • 7
  • 19
  • I think it's all about kerning (https://en.wikipedia.org/wiki/Kerning). TTF file contains character pairs, that are different in width than each character separately. – saNs Aug 18 '19 at 19:03
  • Could also be some sort of automatic letter-spacing …? – misorude Aug 19 '19 at 08:01
  • @misorude how can i fix it? i want them to be equal – tttaaabbb Aug 19 '19 at 13:43
  • If it is due to anything like letter-spacing, then you can only try and figure out a common factor yourself, I think. Or use your own function to write text into the image, that lets you specify the letter-spacing, by actually drawing each letter individually to begin with - https://stackoverflow.com/questions/6926613/php-imagettftext-letter-spacing – misorude Aug 19 '19 at 13:47

0 Answers0