Despite what Barand said, you won't have to do it for every character individually, just for the string. PHP has this nifty little function called imagettftextbbox(), or a bounding TTF box. The bounding box has the coordinates that the string takes up. To get the width, use something like this:
$size = imagettfbbox($textsize,0,"fonts/".$fontfile.".ttf",$line);
$tw = abs($size[4]-$size[0]);
$upper = abs($size[5]);
$under = $size[1];
$th = $upper+$under;
imagettftext($im,$textsize,0,0,0+$upper,$black,"fonts/".$fontfile.".ttf",$line);
$tw is the width and $th is the height. I don't know where I got the width and height correction code snip, but I think it was right off imagettfbbox()'s page.
Hope this helps.