效果图
<?php
//首先生成随机数
$arr = array_merge(range('A','Z'),range('a', 'z'),range(0,9)); //得到一个包含A-Z,a-z,0-9的数组
//打乱数组
shuffle($arr);
//获取随机4个数组的下标
$arr1 = array_rand($arr,4);
$str = ""; //保存验证码
//遍历$arr1得到具体的数字
foreach ($arr1 as $index) {
$str .= $arr[$index];
}
$width = 100; //画布宽
$height = 30; //花布高
//创建一个真彩色画布
$img = imagecreatetruecolor($width,$height);
// 设设置画布的颜色
$imgcolor = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,240),mt_rand(0,220));
// 画一矩形并填充
imagefilledrectangle($img, 0, 0, 100, 30, $imgcolor);
$fontfile = 'd:/www/htdoc/captcha/images/msyh.ttc'; //字体文件ttf的路径
$font = 25; //字体大小
$angle = 0; //旋转角度
// 将随机验证码画到画布上
foreach ($arr1 as $key=>$index) {
$x = $width/4 * $key + mt_rand(5,10);
$y = 28 + mt_rand(3,5);
$captcha = $arr[$index];
$fontcolor = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,240),mt_rand(0,220));//字的颜色
imagettftext($img, $font, $angle, $x, $y, $fontcolor, $fontfile, $captcha);
}
// 设置像素点干扰
for($i=1;$i<300;$i++){
// 像素点的颜色
$pixcolor = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,240),mt_rand(0,220));
// 将像素点画到画布上
imagesetpixel($img,mt_rand(1,99),mt_rand(0,29),$pixcolor);
}
//设置干扰线
for($i=1;$i<6;$i++){
// 像素点的颜色
$linecolor = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,240),mt_rand(0,220));
// 将像素点画到画布上
imageline($img, mt_rand(0,99), mt_rand(0,29),mt_rand(0,99), mt_rand(0,29), $linecolor);
}
// 在浏览器上显示图片
header('Content-Type:image/png');
imagepng($img);
//释放资源
imagedestroy($img);