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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
|
<?php
class Verificationcode
{
protected $width;
protected $height;
protected $len;
public $imgsource;
protected $size;
protected $fontfile;
protected $rescode;
public function __construct($w = 200, $h = 50, $len = 4, $size = null)
{
$this->width = $w;
$this->height = $h;
$this->len = $len;
$this->size = is_null($size) ? $h * 0.4 : $size;
$this->fontfile = realpath("source.ttf");
}
public function render()
{
$this->bg();
$this->line();//文字下
$this->text();
$this->line();//文字上
$this->pix();
$this->show();
return $this->rescode;
}
//绘制画布
private function bg()
{
$img = imageCreateTrueColor($this->width, $this->height);
$this->imgsource = $img;
imagefill(
$img,
0,
0,
imageColorAllocate($img, 120, 120, 120)
);
}
//绘制随机线条
private function line()
{
for ($i = 0; $i < 3; $i++) {
imagesetthickness($this->imgsource, mt_rand(1, 3));
imageLine(
$this->imgsource,
mt_rand(0, $this->width),
mt_rand(0, $this->height),
mt_rand(0, $this->width),
mt_rand(0, $this->height),
$this->ran_color()
);
}
}
//绘制干扰点
private function pix()
{
for ($i = 0; $i < 800; $i++) {
imagesetpixel(
$this->imgsource,
mt_rand(0, $this->width),
mt_rand(0, $this->height),
$this->ran_color()
);
}
}
//随机文本
private function text()
{
$range = "abcdefghijklmnopqrstuvwxyz0123456789";
$code = '';
for ($i = 0; $i < $this->len; $i++) {
$text = $range[mt_rand(0, strlen($range) - 1)];
$box = imagettfbbox($this->size, 0, $this->fontfile, $range[$i]);
imagettftext(
$this->imgsource,
$this->size,
mt_rand(-30, 30),
($this->width / $this->len) * $i + 10,
$this->height / 2 + ($box[0] - $box[7]) / 2,
$this->ran_text_color(),
$this->fontfile,
strtoupper($text)
);
$code .= strtoupper($text);
}
$this->rescode = $code;
}
//设置头信息并且输出png
private function show()
{
header('Content-type:image/png');
imagepng($this->imgsource);
}
private function ran_color()
{
return imageColorAllocate(
$this->imgsource,
mt_rand(0, 255),
mt_rand(0, 255),
mt_rand(0, 255),
);
}
private function ran_text_color()
{
return imageColorAllocate(
$this->imgsource,
mt_rand(0, 80),
mt_rand(0, 80),
mt_rand(0, 80),
);
}
}
|