Reputation: 2385
I want write some text on an jpg. I'm using the php function "imagefttext". The problem is, I want to specify the width of the text box.
In other words: How to write text in a 300px x 300px area on a 900px x 400px image.
How can I do this?
Upvotes: 1
Views: 867
Reputation: 2187
This article should help:
//Had to remove because of new user limitations
Along with: http://uk.php.net/manual/en/ref.image.php
Edit since you don't seem to want to go look for yourself ;)
This provides a function to look up the bounding box of text. http://php.net/manual/en/function.imagettfbbox.php
$box = @ImageTTFBBox($font_size,0,$font_file,$text) ;
$text_width = abs($box[2]-$box[0]);
$text_height = abs($box[5]-$box[3]);
$image_width = imagesx($image);
$text_x = $image_width - $text_width - ($image_width - $x_finalpos);
That should at the very least get you started. There are more detailed examples on the php manual page I linked :)
Edit: Sorry I miss read your question slightly. You need to write a function that checks the length of each line and splits it down until it fits within your specified bounding box. Basically remeasure and keep doing so until it fits. I have also just noticed there are some functions in the comments just below on the php manual page to wrap text which would also give you a good place to start from! :)
Please note this is NOT my code, just copied across from the comments of PHP manual.
<?php
$mx = imagesx($main_img);
$my = imagesy($main_img);
//TEXT VARS/////////
$main_text = ;
$main_text_size = ;
$main_text_x = ($mx/2);
$main_text_color = imagecolorallocate($main_img, $main_text_red, $main_text_green, $main_text_blue);
$words = explode(' ', $main_text);
$lines = array($words[0]);
$currentLine = 0;
for($i = 1; $i < count($words); $i++)
{
$lineSize = imagettfbbox($main_text_size, 0, $mt_f, $lines[$currentLine] . ' ' . $words[$i]);
if($lineSize[2] - $lineSize[0] < $mx)
{
$lines[$currentLine] .= ' ' . $words[$i];
}
else
{
$currentLine++;
$lines[$currentLine] = $words[$i];
}
}
$line_count = 1;
// Loop through the lines and place them on the image
foreach ($lines as $line)
{
$line_box = imagettfbbox($main_text_size, 0, $mt_f, "$line");
$line_width = $line_box[0]+$line_box[2];
$line_height = $line_box[1]-$line_box[7];
$line_margin = ($mx-$line_width)/2;
$line_y = (($line_height+12) * $line_count);
imagettftext($main_img, $main_t_s, 0, $line_margin, $line_y, $main_text_color, $mt_f, $line);
// Increment Y so the next line is below the previous line
$line_count ++;
}
?>
I haven't tested this and there is most probably far better examples out there. Try looking in the php manual comments or look on google for "PHP image text wrap" you'll find something :)
Have fun!
Upvotes: 1