我有一个脚本,使用
PHP从文本生成图像.它工作正常,除了我希望它生成多行文本以及不同的颜色.如何使用PHP,GD和Freetype完成?下面是我用来生成单行文本图像的代码.
$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,$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,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,2)); $green = hexdec(substr($textcolor,2)); $blue = hexdec(substr($textcolor,2)); $tx = imagecolorallocate($png,$blue); imagettftext( $png,$size,$textx,$texty,$tx,$textval ); header("content-type: image/jpeg"); imagejpeg($png); imagedestroy($png); exit;
添加此函数以在文本进入函数之前包装文本.
原文链接:https://www.f2er.com/php/134274.htmlfunction wrap($fontSize,$angle,$fontFace,$string,$width){ $ret = ""; $arr = explode(' ',$string); foreach ( $arr as $word ){ $teststring = $ret.' '.$word; $testBox = imagettfbBox($fontSize,$teststring); if ( $testBox[2] > $width ){ $ret.=($ret==""?"":"\n").$word; } else { $ret.=($ret==""?"":' ').$word; } } return $ret; }