加载GD库
PHP5以上默认已经安装GD库,在php.ini将“;extension=php_gd2.dll”中的分号删除并重启服务器即可生效;
通过phpinfo()函数获取安装信息;
Jpgraph的安装与配置
下载Jpgraph解压缩至一个路径,并在php.ini中添加“include_path=‘Jpgraph的路径’”,重启服务器即可生效;
创建图像
header ('Content-type: image/gif');//定义输出图像类型
$img = imagecreate(200,60);//创建画布设置长宽
$white = imagecolorallocate($img,255,60,60);//给画布添加颜色
imagegif($img);//输出画布
注意:创建画布页面不能有除php以外的标签不然会无法显示
在图像上添加文字
header ('Content-type: image/gif');//输出图像类型
$img = imagecreatefromgif("img/logo.gif");//载入图像
$txtcolor = imagecolorallocate($img,60,60,60);//设置字体颜色
$fnt = "ziti/msyh.ttf";//设置导入字体
$txt = iconv("gb2312","utf-8","这是文字");//只能接受utf-8编码,转换编码
imageTTFText($img,20,10,0,50,$txtcolor,$fnt,$txt);//数字参数依次为:字体大小、水平角度、x、y
imagegif($img);//输出图像
imagedestroy($img);//销毁图片
生成验证码图片
header ('Content-type: image/png');//输出图像类型
$w = 80; //图像宽度
$h = 20; //图像高度
$img = imagecreate($w,$h); //创建画布
$white = imagecolorallocate($img,255,200,60); //画布颜色
$n = "";
for($i=0;$i<4;$i++){
$n .= dechex(rand(0,15)); //制造一个4位随机数并转换为16进制显示
}
for($i=0;$i<strlen($n);$i++){
$x = rand(1,8)+$w*$i/4;//定义输出数字的x坐标
$y = rand(1,$h/4);//定义输出数字的y坐标
$txtcolor = imagecolorallocate($img,rand(0,200),rand(0,200),rand(0,200));//输出数字的颜色
imagestring($img,rand(8,16),$x,$y,$n[$i],$txtcolor);//根据上面的参数将每一位输出在画布上
}
imagepng($img);//生成图片
imagedestroy($img);//销毁图片,释放资源