I did something like this for a shoutcast radio, let's see if it helps:
Variables you need:
$text: the actual string you want to output
$size: the size of the font
$angle: the angle of the font (0 for horizontal)
$maxlen: the maximum length that should be allowed (for 300px it's ok to set 290 in here)
code:
$slices = explode(' ',$text);
$split = count($slices);
do{
$split--;
$out1 = NULL;
for($i=0;$i<=$split;$i++)
{
$out1 .= $slices[$i]." ";
}
$break = imagettfbbox($size,$angle,$fontpath,$out1);
} while ($break[2] > $maxlen);
$out2 = NULL;
for($j=$i; $j<count($slices); $j++)
{
$out2 .= $slices[$j].' ';
}
Once this is run, you will have following values:
$break[2] will tell you the width of the line
$out1 will be the first line and its width will be $break[2]
$out2 the second line
After this you can use both strings and print them into the image using imagettftext:
code:
$im = imagecreate($break[2]+10,50);
$background_color = imagecolorallocate($im, 100, 100, 100);
$text_color = imagecolorallocate($im, 000, 000, 200);
imagecolortransparent($im, $background_color);
imagettftext($img,$size,$angle, 5, 15, $text_color, $font, $out1."\n\r".$out2);
imagegif($im);
imagedestroy($im);
This may work, but if you are intending to do a transparent image with text you will get very ugly text borders. Either use a background or a PNG24 format.