(1)imagecreatetruecolor:创建画布
(2)imagecolorallocate:为画布分配颜色
(3)imagefill:画布填充颜色
(4)imagesetpixel:设置干扰点
(5)imageline:设置干扰线
(6)imagestring:水平地画一行字符串
(7)imagepng:以 png格式将图像输出到浏览器或文件
(8)imagedestroy:销毁图片
创建画布 -> 为画布定义背景颜色 -> 填充背景颜色 -> 设置干扰点 -> 设置干扰线 -> 把字符串填充到画布 -> 设置header向浏览器输出图片 -> 输出图片到浏览器 -> 销毁图片
define("WIDTH", 200);
define("HEIGHT", 50);
//1.创建画布
$image = imagecreatetruecolor(WIDTH, HEIGHT);
//2.为画布定义背景颜色
$bgcolor = imagecolorallocate($image, 255, 255, 255);
//3.填充背景颜色
imagefill($image, 0, 0, $bgcolor);
//4.设置干扰点
for ($i = 0; $i < 200; $i++) {
$pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
imagesetpixel($image, mt_rand(0, WIDTH), mt_rand(0, HEIGHT), $pointcolor);
}
//5.设置干扰线
for ($i = 0; $i < 3; $i++) {
$linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
imageline($image, mt_rand(0, WIDTH), mt_rand(0, HEIGHT), mt_rand(0, WIDTH), mt_rand(0, HEIGHT), $linecolor);
}
$type=mt_rand(0,1);
if($type==0){
$num1=mt_rand(0, 99);
$num2=mt_rand(0, 99);
$cal="+-";
$captcha=$num1.$cal[mt_rand(0, strlen($cal)-1)].$num2.‘=‘;
$captchaLen=strlen($captcha);
$distance=WIDTH/2.0/$captchaLen;
for ($i = 0; $i < $captchaLen; $i++) {
// 字体颜色
$fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
// 设置字体内容
$fontcontent = substr($captcha, $i, 1);
// 设置字符的xy坐标
$x = WIDTH/2.0- $distance*$captchaLen/2+$i* $distance;
$y = mt_rand(5, 30);
// 6.把字符串填充到画布
imagestring($image,30, $x, $y, $fontcontent, $fontcolor);
}
}else{
$captcha=‘2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY‘;
$captchaLen=4;
$distance=WIDTH/2.0/$captchaLen;
for ($i = 0; $i < $captchaLen; $i++) {
// 字体颜色
$fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
// 设置字体内容
$fontcontent = $captcha[mt_rand(0, strlen($captcha)-1)];
// 设置字符的xy坐标
$x = WIDTH/2.0- $distance*$captchaLen/2+$i* $distance;
$y = mt_rand(5, 30);
// 6.把字符串填充到画布
imagestring($image,30, $x, $y, $fontcontent, $fontcolor);
}
}
//7.向浏览器输出图片头信息
header(‘content-type:image/png‘);
//8.输出图片到浏览器
imagepng($image);
//9.销毁图片
imagedestroy($image);
原文:https://www.cnblogs.com/legendheng/p/9086035.html