如何在多行(段落中)中写入文本?

时间:2012-12-30 11:31:22

标签: php imagettftext

当我使用这段代码时,我可以用文字制作图像,但只需一行,

function writetext($image_path,$imgdestpath,$x,$y,$angle,$text,$font,$fontsize) {
      $image=imagecreatefromjpeg("$image_path");
      $height = imageSY($image);
      $width = imageSX($image);
      $color = imagecolorallocate($image,0,0,0);
      $textwidth = $width;
      imageTTFtext($image,$fontsize,$angle,$x,$y,$color,$font, $text );
      ImageJPEG($image,$imgdestpath);
}

请告诉我如何在多行段落中制作此图片?

2 个答案:

答案 0 :(得分:7)

对于每一行,您需要使用$ y的新值调用新的imageTTFtext函数 例如:

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer non nunc lectus.     Curabitur hendrerit bibendum enim dignissim tempus. Suspendisse non ipsum auctor metus consectetur eleifend. Fusce cursus ullamcorper sem nec ultricies. Aliquam erat volutpat. Vivamus massa justo, pharetra et sodales quis, rhoncus in ligula. Integer dolor velit, ultrices in iaculis nec, viverra ut nunc.';

// Break it up into pieces 125 characters long
$lines = explode('|', wordwrap($text, 115, '|'));

// Starting Y position
$y = 513;

// Loop through the lines and place them on the image
foreach ($lines as $line)
{
imagettftext($image, $font_size, 0, 50, $y, $font_color, $font, $line);

// Increment Y so the next line is below the previous line
$y += 23;
}

source

答案 1 :(得分:0)

function writeonimage(){ 

// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('wp-content/themes/ibestquotes/images/background.jpg');

// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 255, 255, 255);

// Set Path to Font File
$font_path = 'wp-content/themes/ibestquotes/fonts/arial-italic.ttf';

// Set Text to Be Printed On Image
$text = get_the_title($_REQUEST['did']);

// Break it up into pieces 25 characters long
$lines = explode('|', wordwrap($text, 25, '|'));

// Starting Y position
$y = 100;

// Loop through the lines and place them on the image
foreach ($lines as $line)
{
imagettftext($jpg_image, 20, 0, 40, $y, $white, $font_path, $line);

// Increment Y so the next line is below the previous line
$y += 40;
}

// Send Image to Browser but we are using download image
//imagejpeg($jpg_image,'wp-content/themes/ibestquotes/name.jpg');


header("Content-type: image/jpeg");  
header("Cache-Control: no-store, no-cache");  
header('Content-Disposition: attachment; filename="avatar.jpg"');
imagejpeg($jpg_image);

// Clear Memory
imagedestroy($jpg_image); 
}


//This code is working on 
http://ibestquotes.com/?t=d&did=56