蓬蓬鹏
2017-06-18 16:27
<?php
session_start();
// 验证码
$img = imagecreatetruecolor(200, 80); // 生成一个彩色图片
$bgcolor = imagecolorallocate($img, 255, 255, 255); // 白色
imagefill($img, 0, 0, $bgcolor); // 填充背景
header('content-type:text/html;charset=utf-8');
// 定义字符集路径
$fontface = "simhei.ttf";
// 定义字符库
$str = "中文字库";
// 如果字符必须保证为 UTF-8 编码格式, 如果不是,需要将其转换UTF-8 编码
// iconv ( string $in_charset , string $out_charset , string $str ) 将 $in_charset 编码的 $str 字符串按要求的 $out_charset 字符编码来转换 并返回
// $str = iconv("GBK", "UTF-8", $text);
// 将字符库中的字符截取成数组
// str_split(string,length) 把字符串分割到数组中。string 要分割的字符串。length 每个数组元素的长度。默认是 1。
// 因为 utf-8 编码的字符 是三个字节一个汉字,所以 length = 3.
$strdb = str_split($str,3);
for ($i=0; $i < 4; $i++) {
// 0-120 为深色区,能更好的在浅色背景中识别验证码
$fontcolor = imagecolorallocate($img, rand(0,120), rand(0,120), rand(0,120));
$index = rand(0,count($strdb)-1);
$cn = $strdb[$index];
$captch .=$cn;
// imagettftext ( 画布资源 , 字体大小 , 倾斜角度 , X轴位置 , Y轴位置 , 字体颜色 , 字符集路径 , 文字内容 ) 图像写入文本
imagettftext($img, rand(14,18), mt_rand(-60,60), (40*$i+20), mt_rand(30,35), $fontcolor, $fontface, $cn);
}
// 保存验证码,并全部转换在小写
$_SESSION['authcode'] = strtolower($captch);
// 加入噪点干扰
for ($i = 0; $i < 200; $i ++) {
$pointcolor = imagecolorallocate($img, rand(50, 200), rand(50, 255), rand(50, 200));
imagesetpixel($img, rand(0, 200), rand(0, 80), $pointcolor); // 随机点生成
}
// 加入线干扰
for ($i = 0; $i < 3; $i ++) {
$linecolor = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($img, rand(0, 200), rand(0, 80), rand(0, 200), rand(0, 80), $linecolor);
}
// 输出验证码
header("content-type: image/png");
imagepng($img);
imagedestroy($img);
我自己的照着写的代码出现这种错误,我还以为我自己写有问题,但是一步步检查发现语法都没问题,就是 imagesetpixel()这里出错,但是又不知道问题所在,上面是网友的代码,我复制粘贴也是一样出错,网上说在header("content-type: image/png");前面加ob_clean();,一样报错,求大师指导。环境是xampp3.2.2,
没毛病,加上去就可以了,。。。。
PHP实现验证码制作
37929 学习 · 336 问题
相似问题