-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcaptcha.go
More file actions
64 lines (56 loc) · 1.21 KB
/
captcha.go
File metadata and controls
64 lines (56 loc) · 1.21 KB
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
package captcha
import (
"image"
"math"
"math/rand"
"github.com/lyp256/captcha/cache"
"github.com/lyp256/captcha/geom"
)
// Captcha 验证码实例
type Captcha struct {
p Provider
c cache.CURD
}
// NewCaptcha 创建验证码实例
func NewCaptcha(p Provider, c cache.CURD) *Captcha {
return &Captcha{
p: p,
c: c,
}
}
// Rand 返回一个随机旋转的图片验证码
func (i *Captcha) Rand(key string) (image.Image, float64, error) {
rad := randRadian()
img, err := i.Draw(key, rad)
if err != nil {
return nil, 0, err
}
return img, rad, nil
}
// Draw 返回一个指定旋转角度的验证码
func (i *Captcha) Draw(key string, rad float64) (image.Image, error) {
img, err := i.p.Get()
if err != nil {
return nil, err
}
err = i.c.Set(key, rad)
if err != nil {
return nil, err
}
// 逆时针旋转
geom.CircleAndRotate(img, rad*-1)
return img, nil
}
// Compare 比较角度
func (i *Captcha) Compare(key string, rad float64) (threshold float64, err error) {
src, err := i.c.Get(key)
if err != nil {
return -1, err
}
return math.Abs(math.Abs(rad) - math.Abs(src)), nil
}
// return [0.14,2π-0.14]
func randRadian() float64 {
const r = 2*math.Pi - 0.28
return 0.14 + (rand.Float64() * r)
}