在PHP中用文本创建IMage – 如何创建多行?
发布时间:2020-12-13 18:01:30 所属栏目:PHP教程 来源:网络整理
导读:我有一个脚本,使用 PHP从文本生成图像.它工作正常,除了我希望它生成多行文本以及不同的颜色.如何使用PHP,GD和Freetype完成?下面是我用来生成单行文本图像的代码. $textval = 'This is some text to be an image';$textcolor = '666666';$font="arial.ttf";$
|
我有一个脚本,使用
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
