这里只介绍非常非常初级的操作。
绘图时一般会经过4个过程:
1、准备好画布,并设定好宽、高以及填充色。
2、在画布上做绘图处理。
3、输出图片
4、清理资源。
在PHP中创建画布大体有二种方式:
1、直接创建一个指定宽高的画布,用imagecreate方法,只需指定宽与高即可。
2、以已有的图片为画图。基本上是在原有的图片上做二次处理。这里会涉及到多种图片格式了,方法名基本上以imagecreatefrom…开头。
创建一种颜色使用imagecolorallocate方法。
输出图片用imagepng/imagegif/imagejpg等方法生成不同格式的图片。
使用imagedestroy方法清理资源。
创建好画布后,就可以用imagestring方法书写文字了。
具体见下面的代码吧:
//要书写的文字
$str=isset($_GET['s']) ? $_GET['s'] : 'yibin001.com';
//画布宽
$imagewidth = 300;
//画布高
$imageheight = 30;
//创建画布
$img = imagecreate($imagewidth,$imageheight);
//为了避免$str过长而无法在画布上完全体现出来,故对字符串做了截取
//imagefontwidth方法用来获取指定大小字体的一个字符的宽度
$StrLength = strlen($str)*imagefontwidth(2);
//将总字符的宽度控制在290以内
while($StrLength>$imagewidth-10)
{
$str = substr($str, 0, strlen($str)-1);
$StrLength = strlen($str)*imagefontwidth(2);
}
//imagecolorallocate方法创建一种颜色,然后填充到画布
imagefill($img, 0,0,imagecolorallocate($img, 200, 0, 123));
$blue = imagecolorallocate($img, 0,0,255);
//计算文字在画布上起点的X与Y轴坐标,下面的算法使文本上下、左右居中
$x = ($imagewidth-(strlen($str)*imagefontwidth(2)))/2;
$y = ($imageheight-imagefontheight(2))/2;
//开始写文字了
imagestring($img,2, $x, $y, $str, $blue);
header('content-type:image/png');
//输出为png格式
imagepng($img);
//清理资源
imagedestroy($img);


