2009-07-08 8 views
7

J'ai un script qui génère des images à partir de texte en utilisant PHP. Cela fonctionne bien sauf que je voudrais qu'il génère du texte multiligne aussi bien avec des couleurs différentes. Comment peut-il être fait en utilisant PHP, GD et Freetype? Ci-dessous le code que j'utilise pour générer des images de texte sur une seule ligne.Création d'IMage à partir de texte en PHP - comment puis-je faire multiline?

$textval = 'This is some text to be an image'; 
$textcolor = '666666'; 


$font="arial.ttf"; 
$size = 9; 
$padding= 1; 
$bgcolor= "ffffff"; 

$transparent = 0; 
$antialias = 0; 

$fontfile = $fontpath.$font; 

$box= imageftbbox($size, 0, $fontfile, $textval, array()); 
$boxwidth= $box[4]; 
$boxheight= abs($box[3]) + abs($box[5]); 
$width= $boxwidth + ($padding*2) + 1; 
$height= $boxheight + ($padding) + 0; 
$textx= $padding; 
$texty= ($boxheight - abs($box[3])) + $padding; 

// create the image 
$png= imagecreate($width, $height); 


$color = str_replace("#","",$bgcolor); 
$red = hexdec(substr($bgcolor,0,2)); 
$green = hexdec(substr($bgcolor,2,2)); 
$blue = hexdec(substr($bgcolor,4,2)); 
$bg = imagecolorallocate($png, $red, $green, $blue); 

$color = str_replace("#","",$textcolor); 
$red = hexdec(substr($textcolor,0,2)); 
$green = hexdec(substr($textcolor,2,2)); 
$blue = hexdec(substr($textcolor,4,2)); 
$tx = imagecolorallocate($png, $red, $green, $blue); 



imagettftext($png, $size, 0, $textx, $texty, $tx, $fontfile, $textval); 

header("content-type: image/jpeg"); 
imagejpeg($png); 
imagedestroy($png); 
exit; 

Répondre

6

Ajoutez cette fonction pour envelopper le texte avant qu'il n'entre dans votre fonction.

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==""?"":"\n").$word; 
     } else { 
      $ret.=($ret==""?"":' ').$word; 
     } 
    } 

    return $ret; 
} 

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

+0

J'ai essayé d'utiliser \ n mais pour une raison quelconque, il imprime également le \ n comme il est :( – Ali

+0

Salut, pouvez-vous me aider à, comment utiliser l'image de fond personnalisée, J'essaie de créer un captcha en utilisant cette fonction – rkaartikeyan

Questions connexes