PHP产生一个验证码,但是只能生成一个灰色方块,不论是修改画布颜色还是添加文字都无法实现。以下是源码和测试结果:
<?php
header('Content-type:text/html;charset=utf-8');
ob_clean();
//生成验证码
//1、创建验证码画布
$img_w = 100; //验证码的宽度
$img_h = 30; //验证码的高度
$img = @imagecreatetruecolor($img_w, $img_h) //创建画布
or die("1") ;
$bg_color = @imagecolorallocate($img,0xcc,0xcc,0xcc) //画布颜色
or die("2") ;
echo("backgound color is $bg_color
");
@imagefill($img,0,0,$bg_color) //背景色
or die("3");
//生成验证码文本
$count = 4; //验证码位数
$charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; //随机因子
$charset_len = strlen($charset)-1 ;//最大索引值。(下标)可以换作strlen($charset)-1
$code = ''; //保存生成的验证码
for($i=0; $i<$count; $i++) {
//通过索引取出字符,mt_rand()用于获取指定范围内的随机数
$code .= $charset[mt_rand(0,$charset_len)];
}
//echo ("code is $code\t
");
//3、将生成的文本保存到Session中
session_start();//启动session
$_SESSION['captcha'] = $code;
//4、在画布中绘制验证码文本
$fontSize = 16; //文字大小
$fontStyle = 'simhei.ttf'; //字体样式
for($i=0; $i<$count; ++$i){
//随机生成字体颜色
$fontColor = @imagecolorallocate($img,mt_rand(0,100),mt_rand(0,50),mt_rand(0,255))
or die("4");
echo("fontcolor$i is $fontColor
");
//数组imagettftext(资源$image,float $size,float $angle int $x,int $y,int $color,string $fontfile,string $text)
@imagettftext($img, $fontSize, mt_rand(0,50) - mt_rand(0,25), $fontSize*$i+20,mt_rand($img_h/2,$img_h), $fontColor, $fontStyle,$code[$i])
or die("5");
}
//5、为验证码图片生成彩色噪点、干扰线
for($i=0; $i<100; ++$i){
//随机生成颜色
$color = @imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255))
or die("6") ;
//随机绘制干扰点
@imagesetpixel($img,mt_rand(0,$img_w),mt_rand(0,$img_h),$color)
or die("7") ;
//随机绘制干扰线
if($i % 20 ==0)
imageline($img,mt_rand(0,$img_w),0,mt_rand(0,$img_h*5),$img_h,$color);
}
@header('Content-Type:image/gif') //声明要发送(也就是浏览器要展现)的文件类型
or die("8");
@imagegif($img)
or die("9");
imagedestroy($img);
?>
尝试修改函数imagecolorallocate的参数还是一直显示这样的图片:
(经过放大了的)
不过这是在把“在画布中绘制验证码文本”这一步注释掉之后才得到的,如果没有将其注释掉,我只能看到一个报错:
换句话说,写入文本这一步也不能进行。 另外,代码也不存在路径问题,即写文本的函数并不是因为找不到.ttf文件而报错的。并且gd也是正常打开的
还请各位帮我看看,究竟问题出在哪??