Write text to image with php

Hellow all,

I have this script thats displays a dynamic text in an image in the browser. This works great, but... When the text is longer than the designated image width the text gets chopped off.

Is there a way to check the text length and split the text into two lines, and also adjust the image height? How can this be done?

Thanks and greetz,
walter
<?
header("Content-type:image/jpeg"); 
 
// -----------------------------------------------------------------------------------
// ---- html entities to html tags php 4 ---------------------------------------------
// -----------------------------------------------------------------------------------
function htmlspecialchars_decode_php4 ($str, $quote_style = ENT_COMPAT) {
    return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
}
 
$theTitle = $_GET['title'];
 
$im = imagecreatetruecolor(575, 40);
	// Create some colors
$background = imagecolorallocate($im, 31, 31, 31);
$frontColor = imagecolorallocate($im, 255, 205, 3);
$backColor = imagecolorallocate($im, 105, 16, 16);
imagefilledrectangle($im, 0, 0, 575, 40, $background);
 
// Replace path by your own font path
$font = '../font/Chernobyl-Regular.otf';
 
// Add the text
imagettftext($im, 22, 0, 3, 27, $backColor, $font, stripslashes(htmlspecialchars_decode_php4(urldecode($theTitle))));
imagettftext($im, 22, 0, 1, 25, $frontColor, $font, stripslashes(htmlspecialchars_decode_php4(urldecode($theTitle))));
 
imagejpeg($im, '', 100);
 
imagedestroy($im);
 
?>

Open in new window

LVL 8
wal_toorAsked:
Who is Participating?
 
nativestudiosCommented:
Hi Walter,

You'll need to work out how many characters you can fit within the width you've specified, then split your string up accordingly.

There are a number of functions posted on php.net that may help you solve this problem:
http://uk.php.net/imagettfbbox

Hope this is of some use to you

Andy
0
 
wal_toorAuthor Commented:
Thanks, got it working! I also used wordwrap to get it right.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.