Creating IMage from Text in PHP - how can I make multiline?

✔ Recommended Answer

Add this function to wrap the text before it goes into your function.

function wrap($fontSize, $angle, $fontFace, $string, $width){    $ret = "";    $arr = explode(' ', $string);    foreach ( $arr as $word ){        $teststring = $ret.' '.$word;        $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);        if ( $testbox[2] > $width ){            $ret.=($ret==""?"":"").$word;        } else {            $ret.=($ret==""?"":' ').$word;        }    }    return $ret;}

Source: http://www.php.net/imagettftext

Source: stackoverflow.com

Answered By: Josh

Method #2

To create an image from text with multiline support in PHP, you can use the imagettftext function along with the wordwrap function to break the text into multiple lines. Here's an example:

php
// Set the font size and font file $font_size = 20; $font_file = 'path/to/font.ttf'; // Set the text to render and wrap it into multiple lines $text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dapibus ante ac erat pharetra, in pretium risus eleifend. Quisque vitae risus libero. Donec tincidunt nibh augue, vel bibendum mauris ultrices in."; $wrapped_text = wordwrap($text, 25, "\n"); // Create a blank image with a width and height large enough to fit the text $image_width = 600; $image_height = 400; $image = imagecreatetruecolor($image_width, $image_height); // Set the background color $background_color = imagecolorallocate($image, 255, 255, 255); imagefill($image, 0, 0, $background_color); // Set the text color $text_color = imagecolorallocate($image, 0, 0, 0); // Calculate the position of the first line of text $line_height = $font_size * 1.5; // add spacing between lines $x = 50; // x position $y = 50; // y position // Loop through the wrapped text and render each line of text foreach (explode("\n", $wrapped_text) as $line) { imagettftext($image, $font_size, 0, $x, $y, $text_color, $font_file, $line); $y += $line_height; // move to the next line } // Output the image header('Content-Type: image/png'); imagepng($image); imagedestroy($image);

In this example, we first set the font size and font file. We then set the text to render and use the wordwrap function to wrap the text into multiple lines with a maximum line length of 25 characters.

We create a blank image with a width and height large enough to fit the text, and set the background color. We then calculate the position of the first line of text based on the font size and line spacing.

Finally, we loop through the wrapped text and render each line of text using imagettftext, and move to the next line by incrementing the y position. We output the image using header and imagepng, and destroy the image using imagedestroy.

Comments

Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755