/
verifycode.go
408 lines (357 loc) · 10.4 KB
/
verifycode.go
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package verifycode
import(
"fmt"
"io"
"io/ioutil"
"strconv"
"math/big"
"crypto/rand"
"strings"
"image"
"image/color"
"image/png"
"image/jpeg"
"image/gif"
"image/draw"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
)
//Rand 随机数,返回的随机数是 0-n 的其中一个值。
// n int 最大限制的数值
// int64 返回0-n的随机数
func Rand(n int) int64 {
if n <= 0 {
return 0
}
max := big.NewInt(int64(n))
rnd, err := rand.Int(rand.Reader, max)
if err != nil {
return 0
}
return rnd.Int64()
}
//RandRange 随机数(范围)
// min, max int 最小值,最大值
// int64 最小至最大范围的值
func RandRange(min, max int) int64 {
return int64(min) + Rand(max+1 - min)
}
//RandomText 随机字符
// text string , n int 字符串,指定长度
// string 返回n个长度的随机字条串
func RandomText(text string , n int) string {
var (
b []rune
length = len([]rune(text))
r int64
)
stringsReader := strings.NewReader(text)
for i:=0; i<n; i++ {
r = Rand(length)
stringsReader.Seek(r, 0)
ch, _, err := stringsReader.ReadRune()
if err != nil {
i--
continue
}
b = append(b, ch)
}
return string(b)
}
//Color 颜色集
type Color struct {
color []color.Color
}
//AddHEX 增加十六进制颜色
// text string 颜色字符串,格式如:#11223344 或 11223344
// error 错误
func (T *Color) AddHEX(text string) error {
var l = len(text)
if text == "" || l < 8 || l > 9 {
return fmt.Errorf("verifycode: 十六进制颜色符长度不符合 %s, 格式如#11223344 或 11223344", text)
}
if l > 8 {
text = text[1:]
}
var e = "verifycode: 颜色 %s,解析错误是 >> %s"
R, err := strconv.ParseInt(text[0:2], 16, 64)
if err != nil {
return fmt.Errorf(e, text, err)
}
G, err := strconv.ParseInt(text[2:4], 16, 64)
if err != nil {
return fmt.Errorf(e, text, err)
}
B, err := strconv.ParseInt(text[4:6], 16, 64)
if err != nil {
return fmt.Errorf(e, text, err)
}
A, err := strconv.ParseInt(text[6:8], 16, 64)
if err != nil {
return fmt.Errorf(e, text, err)
}
if (R <= 255 && R >= 0) && (G <= 255 && G >=0) && (B <= 255 && B >= 0) && (A <= 255 && A >= 0) {
T.color = append(T.color, color.RGBA{uint8(R), uint8(G), uint8(B), uint8(A)})
return nil
}
return fmt.Errorf("verifycode: 颜色不正确 %s", text)
}
//AddRGBA 增加RGBA颜色
// r, g, b, a uint8 RGBA颜色值0-255
// error 错误
func (T *Color) AddRGBA(r, g, b, a uint8) error {
if (r <= 255 && r >= 0) && (g <= 255 && g >=0) && (b <= 255 && b >= 0) && (a <= 255 && a >= 0) {
T.color = append(T.color, color.RGBA{r, g, b, a})
return nil
}
return fmt.Errorf("verifycode: 参数颜色值仅限于0-255范围")
}
//Random 随机颜色
// color.Color 颜色,如果没有自定义的颜色,否则内部自动生成一个随机颜色
func (T *Color) Random() color.Color {
var (
cLen = len(T.color)
n = Rand(cLen)
)
if cLen == 0 {
//随机生成一个颜色
return color.RGBA{
R: uint8(RandRange(128, 255)),
G: uint8(RandRange(128, 255)),
B: uint8(RandRange(128, 255)),
A: uint8(RandRange(128, 255)),
}
}
//随机读取列表中的一个颜色
return T.color[n]
}
//Font 字体
type Font struct {
font []*truetype.Font // 字体集
}
//AddFile 增加字体文件
// src string 字体文件路径
// error 错误
func (T *Font) AddFile(src string) error {
b, err := ioutil.ReadFile(src)
if err != nil {
return err
}
font, err := truetype.Parse(b)
if err != nil {
return err
}
T.font = append(T.font, font)
return nil
}
//Random 随机字体
// *truetype.Font 字体对象
// error 错误
func (T *Font) Random() (*truetype.Font, error) {
var fLen = len(T.font)
if fLen == 0 {
return nil, fmt.Errorf("verifycode: 没有可用的字体")
}
n := Rand(fLen)
f := T.font[n]
return f, nil
}
//Glyph 字形
type Glyph struct{
Hinting font.Hinting // 微调字形
Size float64 // 字形大小
DPI float64 // PDI,默认72
}
//FontGlyph 字体字形
// Font *truetype.Font 字体对象
// text rune 单个文字
// c image.Image 颜色
// draw.Image 字形
// error 错误
func (T *Glyph) FontGlyph(Font *truetype.Font, text rune, c color.Color) (draw.Image, error) {
//字形大小是字体文件已经固定,各字体文件的字形大小不一。
perEm := Font.FUnitsPerEm()
//生成的字体大小,必须按字形比例来计算缩放。是大还是小。
ratio := T.Size/float64(perEm)
//生成的图片一样的宽和高
wh := int(float64(perEm)*ratio)
//各字体中的字形的高度不一样,需要计算Y的位置
b := Font.Bounds(fixed.Int26_6(perEm))
//y轴是从字高开始
//vMetric := Font.VMetric(fixed.Int26_6(perEm), Font.Index(text))
fontHeight := int(b.Max.Y+b.Min.Y)
y := (int(perEm)-fontHeight)/2+fontHeight
//x轴是从0开始
hMetric := Font.HMetric(fixed.Int26_6(perEm), Font.Index(text))
x := (int(perEm)-int(hMetric.LeftSideBearing)-int(hMetric.AdvanceWidth))/2
// 新建一个 指定大小的 RGBA位图
var dx, dy = wh, wh
drawImage := image.NewRGBA(image.Rect(0, 0, dx, dy))
//for i:=0;i<dx;i++ {
// for j:=0;j<dy;j++{
// drawImage.Set(i, j, color.RGBA{R: 0, G: 0, B: 0, A: 255, })
// }
//}
//字体转图片
freetypeContext := freetype.NewContext();
freetypeContext.SetClip(drawImage.Bounds())
if T.DPI > 0 && T.DPI < 72 {
// freetypeContext.SetDPI(T.DPI)
}
freetypeContext.SetFont(Font)
freetypeContext.SetFontSize(T.Size)
freetypeContext.SetHinting(T.Hinting)
freetypeContext.SetSrc(image.NewUniform(c))
freetypeContext.SetDst(drawImage)
pt := freetype.Pt(int(float64(x)*ratio), int(float64(y)*ratio))
pt, err := freetypeContext.DrawString(string(text), pt)
return drawImage, err
}
//VerifyCode 验证码
type VerifyCode struct {
Width, Height int // 宽,高
DPI float64 // DPI
style []*Style // 多种配色方案
}
//Style 本色
type Style struct{
Font *Font // 字体对象
Size float64 // 字体大小
TextColor, BackgroundColor *Color // 颜色,背景
Hinting font.Hinting // 微调
TextSpace int // 间距
}
//Style 多种配色方案,可以多次调用来增加多个配色方案。
// error 错误
func (T *VerifyCode) Style(s *Style) error {
if s == nil {
return fmt.Errorf("verifycode:配色不可以是nil")
}
T.style = append(T.style, s)
return nil
}
func backgroundColorBlock(v int) int {
return int(RandRange(int(float32(v)*0.2), int(float32(v)*0.4)))+1
}
//Draw 水印
func (T *VerifyCode) Draw(text string) (draw.Image, error) {
//读取配色
if T.style == nil {
return nil, fmt.Errorf("verifycode:没有配色可以使用")
}
sn := Rand(len(T.style))
if T.style[sn] == nil {
return nil, fmt.Errorf("verifycode:配色是空接口")
}
style := T.style[sn]
if style.Font == nil {
return nil, fmt.Errorf("verifycode:配色中没有携带字体")
}
if style.TextColor == nil {
style.TextColor=&Color{}
}
if style.BackgroundColor == nil {
style.BackgroundColor = &Color{}
}
//绘制一个框大小,也可以说是一张背景
imageRectangle := image.Rect(0, 0, T.Width, T.Height)
imageRGBA := image.NewRGBA(imageRectangle)
//绘制背景颜色
var(
bgRandH = backgroundColorBlock(T.Width)
bgRandV = backgroundColorBlock(T.Height)
bgColor color.Color
yColors = make(map[int]color.Color)
)
yColors[0]=style.BackgroundColor.Random()
for x := 0; x<T.Width; x++ {
if (x+1)%bgRandH == 0 {
bgRandH = backgroundColorBlock(T.Width)
yColors = make(map[int]color.Color)
yColors[0]=style.BackgroundColor.Random()
}
for y := 0; y<T.Height; y++ {
if bgc, ok := yColors[y]; ok {
bgColor = bgc
}else if (y+1)%bgRandV == 0 {
bgRandV = backgroundColorBlock(T.Height)
yColors[y]=style.BackgroundColor.Random()
bgColor = yColors[y]
}else{
yColors[y] = bgColor
}
imageRGBA.Set(x, y, bgColor)
}
}
var(
sp image.Point
x, y int
sizeI = int(style.Size)
fontLength = len([]rune(text))
fontWidth = T.Width/fontLength
rnd int
i int
glyph = Glyph{
Size:style.Size,
DPI:T.DPI,
Hinting:style.Hinting,
}
)
for _, v := range text {
f, err := style.Font.Random()
if err != nil {
//字体错误
return nil, err
}
drawImage, err := glyph.FontGlyph(f, v, style.TextColor.Random())
if err != nil {
return nil, err
}
//位置是负
rnd = int(RandRange(^style.TextSpace, style.TextSpace))
x = ^(int(fontWidth*i)+int((float64(fontWidth)-style.Size)*0.5)+rnd)
//位置是负
y = ^int(RandRange(sizeI, T.Height)) + sizeI
sp = image.Pt(x, y)
draw.Draw(imageRGBA, imageRectangle, drawImage, sp, draw.Over)
i++
}
return imageRGBA, nil
}
//PNG 生成PNG图片
// text string 文本
// w io.Writer 写入接口
// error 错误
func (T *VerifyCode) PNG(text string, w io.Writer) error {
imageImage, err := T.Draw(text)
if err != nil {
return err
}
return png.Encode(w, imageImage)
}
//GIF 保存为GIF格式图片
// text string 文本
// w io.Writer 写入接口
// opt *gif.Options 控制图片质量
// error 错误
func (T *VerifyCode) GIF(text string, w io.Writer, opt *gif.Options) error {
imageImage, err := T.Draw(text)
if err != nil {
return err
}
return gif.Encode(w, imageImage, opt)
}
//JPEG 保存为JPEG格式图片
// text string 文本
// w io.Writer 写入接口
// opt *jpeg.Options 控制图片质量
// error 错误
func (T *VerifyCode) JPEG(text string, w io.Writer, opt *jpeg.Options) error {
imageImage, err := T.Draw(text)
if err != nil {
return err
}
return jpeg.Encode(w, imageImage, opt)
}