Page 1 of 1

quick question related to imagestring.

Posted: Sat May 27, 2006 1:55 pm
by Flamie
So if I have a rectangle:

Code: Select all

$TopLeftX = whatever;
$TopLeftY = whatever2;
$width = we;
$height = we2;
and I have a string $message, is there an easy way for me to make it fit in that box (like having it go to the line when it reaches the end of the rectangle?

Posted: Thu Jun 08, 2006 5:13 am
by onion2k
Pretty easy .. you'd need to work out the maximum length of text that will fit in the box (with imagefontwidth() ), then use wordwrap() .. or write your own wrapping function if wordwrap() isn't up to it (depends, wordwrap() isn't all that clever). That's if you're using PHP's builtin fonts. If you're using TTF, PS, etc fonts then you'll need to use the bounding box functions (imagettfbbox() for example), and loop through your text adding one letter at a time until you reach the maximum width, then draw the line, and move down to the next. Tedious, but it'll work.

Re: quick question related to imagestring.

Posted: Thu Jun 08, 2006 6:33 am
by bokehman
Flamie wrote:is there an easy way for me to make it fit in that box
Check this thread. I used precisely the method Onion2k describes.

Posted: Thu Jun 08, 2006 6:52 am
by bokehman
More...

Image

Code: Select all

<?php

function OutputTextAsImage($text, $image_width = 300, $colour = array(0,0,0), $background = array(255,255,159), $padding = NULL, $destination = NULL)
{
	$font = 5; // that's the biggest
	$line_height = ImageFontheight($font) + 5;
	$padding = (is_numeric($padding)) ? $padding : 10;
	$quality = 75; // 0 = worst, 100 = best
	$text = wordwrap($text, (($image_width - (1.5 * $padding))/ImageFontWidth($font)));
	$lines = explode("\n", $text);
	$image = imagecreate($image_width,((count($lines) * $line_height)) + ($padding * 2));
	$background = imagecolorallocate($image, $background[0], $background[1], $background[2]);
	$colour = imagecolorallocate($image,$colour[0],$colour[1],$colour[2]);
	imagefill($image, 0, 0, $background);
	$i = $padding;
	foreach($lines as $line){
		imagestring($image, $font, $padding, $i, trim($line), $colour);
		$i += $line_height;
	}
	$destination or header('Content-Type: image/jpeg');
	imagejpeg($image, null, $quality);
	imagedestroy($image);
	$destination or die;
}

$text = <<<END
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer commodo consequat lacus. 

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
 
Vivamus eu neque. Maecenas ut erat in turpis ornare rutrum. Duis id leo. Proin elit tortor, porta a, elementum nec, ultrices sed, ante. 
END;

OutputTextAsImage($text)

?>