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
package cn.chnmuseum.party.common.checkcode;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
/**
* <p>
* png格式验证码
* </p>
*
* @author: wuhongjun
* @version:1.0
*/
public class SpecCaptcha extends Captcha {
public SpecCaptcha() {
}
public SpecCaptcha(int width, int height) {
this.width = width;
this.height = height;
}
public SpecCaptcha(int width, int height, int len) {
this(width, height);
this.len = len;
}
public SpecCaptcha(int width, int height, int len, Font font) {
this(width, height, len);
this.font = font;
}
/**
* 生成验证码
*
* @throws IOException IO异常
*/
@Override
public String out(OutputStream out) {
return graphicsImage(alphas(), out);
}
/**
* 画随机码图
*
* @param strs 文本
* @param out 输出流
*/
private String graphicsImage(char[] strs, OutputStream out) {
try {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();
AlphaComposite ac3;
Color color;
int len = strs.length;
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 随机画干扰的蛋蛋
for (int i = 0; i < 15; i++) {
color = color(150, 250);
g.setColor(color);
g.drawOval(num(width), num(height), 5 + num(10), 5 + num(10));// 画蛋蛋,有蛋的生活才精彩
color = null;
}
g.setFont(font);
int h = height - ((height - font.getSize()) >> 1), w = width / len, size = w - font.getSize() + 1;
/* 画字符串 */
for (int i = 0; i < len; i++) {
ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);// 指定透明度
g.setComposite(ac3);
color = new Color(20 + num(110), 20 + num(110), 20 + num(110));// 对每个字符都用随机颜色
g.setColor(color);
g.drawString(strs[i] + "", (width - (len - i) * w) + size, h - 4);
color = null;
ac3 = null;
}
ImageIO.write(bi, "JPEG", out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return String.valueOf(strs);
}
}