3

I want to write a wrapped text to a image with php. Here is a demo. If you copy, paste and send text below to demo you will notice that some lines are distorted and there is some paragraph spaces which must not be there. I am looking to the code for hours. I couldn't understand where is the problem. Is there anybody help me?

Sample Text:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut justo consectetur, cursus lorem vitae, accumsan lorem. Cras eu odio vulputate, rhoncus dui vel, aliquam lorem. Fusce scelerisque facilisis lacus, quis malesuada justo placerat nec. Curabitur elementum mattis nisl, sed sodales mauris congue et. Nunc velit mauris, accumsan a dictum vitae, pellentesque luctus leo. Maecenas in venenatis orci. Suspendisse sed neque magna. Praesent vitae sapien porttitor diam aliquam eleifend. Maecenas lacinia elit non velit vehicula rutrum. Sed ultricies mauris vitae dapibus tempor. Praesent eros metus, euismod ut est eget, rhoncus iaculis lorem. Ut aliquet dictum ligula lobortis cursus. Sed mattis ante ut odio tincidunt venenatis. Donec euismod quam sit amet velit tincidunt, ut convallis ligula tempor. Quisque tincidunt elit sem, quis laoreet orci accumsan in.

$mx = imagesx($im);   // Width of the created image
$my = imagesy($im);   // Height of the image

//TEXT VARS/////////
$main_text = $text;   // $text variable comes directly from the form
$main_text_size = 20; // $text font size

$words = explode(' ', $main_text);
$lines = array($words[0]);
$currentLine = 0;

    for($i = 1; $i < count($words); $i++)
    {
        $lineSize = imagettfbbox($main_text_size, 0, $font, $lines[$currentLine] . ' ' . $words[$i]);
        if($lineSize[2] - $lineSize[0] < ($mx-20))
        {
            $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, $font, "$line");
    $line_height = $line_box[1]-$line_box[7];
    $line_y = (($line_height+4) * $line_count);
    imagettftext($im, $main_text_size, 0, 5, $line_y, $black, $font, $line);

    // Increment Y so the next line is below the previous line
    $line_count ++;
}   

imagepng($im, 'image.png');
imagedestroy($im);
mcan
  • 1,914
  • 3
  • 32
  • 53
  • Have you included all the relevant code because I'm getting quite a few errors when just trying to set up a test site? – Laniakea Sep 04 '13 at 11:06
  • @MartinMetsalu First of all, You have to define the `$im` an set it a background color and define `$black`, `$yellow`, `$font` variables. I didn't put these parts here. – mcan Sep 04 '13 at 11:15
  • Why are you doing this? "$words = explode(' ', $main_text); $lines = array($words[0]);". $words[0] will be the first word of $main_text. – Manolo Sep 08 '13 at 09:03

0 Answers0