在PHP中用文本创建IMage – 如何创建多行?

前端之家收集整理的这篇文章主要介绍了在PHP中用文本创建IMage – 如何创建多行?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个脚本,使用 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;
添加函数以在文本进入函数之前包装文本.
function 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;
}

资料来源:http://www.php.net/imagettftext

猜你在找的PHP相关文章