|
1
|
|
|
<?php |
|
2
|
|
|
namespace app\libraries; |
|
3
|
|
|
|
|
4
|
|
|
// 验证码类 |
|
5
|
|
|
class Captcha |
|
6
|
|
|
{ |
|
7
|
|
|
private $chararr = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; |
|
8
|
|
|
private $code; |
|
9
|
|
|
private $codelen = 4; |
|
10
|
|
|
private $width = 120; |
|
11
|
|
|
private $height = 40; |
|
12
|
|
|
private $img; |
|
13
|
|
|
private $font; |
|
14
|
|
|
private $fontsize = 20; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct() |
|
17
|
|
|
{ |
|
18
|
|
|
$this->font = __DIR__ . '/font.ttf'; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
// 生成随机码 |
|
22
|
|
|
private function createCode() |
|
23
|
|
|
{ |
|
24
|
|
|
$_len = strlen($this->chararr) - 1; |
|
25
|
|
|
for ($i = 0; $i < $this->codelen; $i++) { |
|
26
|
|
|
$this->code .= $this->chararr[mt_rand(0, $_len)]; |
|
27
|
|
|
} |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
// 生成背景 |
|
31
|
|
|
private function createBg() |
|
32
|
|
|
{ |
|
33
|
|
|
$this->img = imagecreate($this->width, $this->height); |
|
34
|
|
|
imagecolorallocatealpha($this->img, 255, 255, 255, 100); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
// 生成验证码 |
|
38
|
|
|
private function createFont() |
|
39
|
|
|
{ |
|
40
|
|
|
$_x = $this->width / $this->codelen; |
|
41
|
|
|
for ($i = 0; $i < $this->codelen; $i++) { |
|
42
|
|
|
$color = imagecolorallocate($this->img, mt_rand(0, 156), mt_rand(0, 156), mt_rand(0, 156)); |
|
43
|
|
|
imagettftext($this->img, $this->fontsize, mt_rand(-50, 50), $_x * $i + mt_rand(5, 10), $this->height / 1.5, $color, $this->font, $this->code[$i]); |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
// 生成干扰元素 |
|
48
|
|
|
private function createLine() |
|
49
|
|
|
{ |
|
50
|
|
|
for ($i = 0; $i < 50; $i++) { |
|
51
|
|
|
$color = imagecolorallocate($this->img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255)); |
|
52
|
|
|
imagestring($this->img, mt_rand(1, 5), mt_rand(0, $this->width), mt_rand(0, $this->height), 'JZ', $color); |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
// 输出 |
|
57
|
|
|
private function outPut() |
|
58
|
|
|
{ |
|
59
|
|
|
header('Content-type: image/png'); |
|
60
|
|
|
imagepng($this->img); |
|
61
|
|
|
imagedestroy($this->img); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
// 对外生成 |
|
65
|
|
|
public function getImg() |
|
66
|
|
|
{ |
|
67
|
|
|
$this->createBg(); |
|
68
|
|
|
$this->createCode(); |
|
69
|
|
|
$this->createLine(); |
|
70
|
|
|
$this->createFont(); |
|
71
|
|
|
$this->outPut(); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
// 获取验证码 |
|
75
|
|
|
public function getCode() |
|
76
|
|
|
{ |
|
77
|
|
|
return strtolower($this->code); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|