1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
class
Chptcha{
private
$width
=200;
private
$height
=100;
private
$chars
=5;
private
$lines
=20;
//干扰点
private
$spots
=600;
public
function
generate(){
//制作画布
$img
=imagecreatetruecolor(
$this
->width,
$this
->height);
//在画布资源下分配颜色,经验,画布颜色要明亮点
$bg
=imagecolorallocate(
$img
,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
//给画布填充颜色
imagefill(
$img
,0,0,
$bg
);
//增加验证码
$captcha
=
$this
->getCaptcha();
$str
=imagecolorallocate(
$img
,mt_rand(50,100),mt_rand(50,100),mt_rand(50,100));
//获取随机位置
//宽度: 使用图片宽度减去文件宽度
$e_width
=
$this
->width -
$this
->chars * 10 - 10;
$e_height
=
$this
->height/2;
//5,代表的是字体的大小
imagestring(
$img
,5,mt_rand(10,
$e_width
),mt_rand(
$e_height
-1,
$e_height
),
$captcha
,
$str
);
$this
->getLines(
$img
);
$this
->getPixels(
$img
);
header(
'content-type:image/png'
);
imagepng(
$img
);
//释放资源
imagedestroy(
$img
);
}
private
function
getCaptcha(){
//产生随机字符串
$str
=
'abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789'
;
$captcha
=
''
;
for
(
$i
= 0;
$i
<
$this
->chars;
$i
++){
$captcha
.=
$str
[mt_rand(0,
strlen
(
$str
) - 1)];
}
//返回
return
$captcha
;
}
private
function
getLines(
$img
){
//增加干扰线
for
(
$i
= 0;
$i
<
$this
->lines;
$i
++){
//分配颜色
$line
= imagecolorallocate(
$img
,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));
//制作线段
imageline(
$img
,mt_rand(0,
$this
->width),mt_rand(0,
$this
->height),mt_rand(0,
$this
->width),mt_rand(0,
$this
->height),
$line
);
}
}
private
function
getPixels(
$img
){
//增加干扰点
for
(
$i
= 0;
$i
<
$this
->spots;
$i
++){
//分配颜色
$pixel
= imagecolorallocate(
$img
,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));
//制作
imagesetpixel(
$img
,mt_rand(0,
$this
->width),mt_rand(0,
$this
->height),
$pixel
);
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//自动加载类函数
header(
'content-type:text/html;charset=utf-8'
);
function
__autoload(
$class
){
$file
=
"$class.class.php"
;
//判断是否是一个文件
if
(
is_file
(
$file
)){
include_once
$file
;
}
}
//创建对象
$chptcha
=
new
Chptcha();
//调用方法
$chptcha
->generate();
|
总结:php做验证码总体不难,灵活运用系统提供的几个函数,以及对颜色的正确的搭配,相信你会做出。