1 public class VerifyCodeController {
2
3 private int width = 90;//定义图片的width
4 private int height = 20;//定义图片的height
5 private int codeCount = 4;//定义图片上显示验证码的个数
6 private int xx = 15;
7 private int fontHeight = 18;
8 private int codeY = 16;
9 char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
10 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
11 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
12
13 @RequestMapping("/getVerifyCode")
14 public void getVerifyCode(HttpServletRequest req, HttpServletResponse resp)
15 throws IOException {
16 // 定义图像buffer
17 BufferedImage buffImg = new BufferedImage(width, height,
18 BufferedImage.TYPE_INT_RGB);
19 // Graphics2D gd = buffImg.createGraphics();
20 //Graphics2D gd = (Graphics2D) buffImg.getGraphics();
21 Graphics gd = buffImg.getGraphics();
22 // 创建一个随机数生成器类
23 Random random = new Random();
24 // 将图像填充为白色
25 gd.setColor(Color.WHITE);
26 gd.fillRect(0, 0, width, height);
27
28 // 创建字体,字体的大小应该根据图片的高度来定。
29 Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
30 // 设置字体。
31 gd.setFont(font);
32
33 // 画边框。
34 gd.setColor(Color.BLACK);
35 gd.drawRect(0, 0, width - 1, height - 1);
36
37 // 随机产生40条干扰线,使图象中的认证码不易被其它程序探测到。
38 gd.setColor(Color.BLACK);
39 for (int i = 0; i < 40; i++) {
40 int x = random.nextInt(width);
41 int y = random.nextInt(height);
42 int xl = random.nextInt(12);
43 int yl = random.nextInt(12);
44 gd.drawLine(x, y, x + xl, y + yl);
45 }
46
47 // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
48 StringBuffer randomCode = new StringBuffer();
49 int red = 0, green = 0, blue = 0;
50
51 // 随机产生codeCount数字的验证码。
52 for (int i = 0; i < codeCount; i++) {
53 // 得到随机产生的验证码数字。
54 String code = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
55 // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
56 red = random.nextInt(255);
57 green = random.nextInt(255);
58 blue = random.nextInt(255);
59
60 // 用随机产生的颜色将验证码绘制到图像中。
61 gd.setColor(new Color(red, green, blue));
62 gd.drawString(code, (i + 1) * xx, codeY);
63
64 // 将产生的四个随机数组合在一起。
65 randomCode.append(code);
66 }
67 // 将四位数字的验证码保存到Session中。
68 HttpSession session = req.getSession();
69 System.out.print(randomCode);
70 session.setAttribute("verifycode", randomCode.toString());
71
72 // 禁止图像缓存。
73 resp.setHeader("Pragma", "no-cache");
74 resp.setHeader("Cache-Control", "no-cache");
75 resp.setDateHeader("Expires", 0);
76
77 resp.setContentType("image/jpeg");
78
79 // 将图像输出到Servlet输出流中。
80 ServletOutputStream sos = resp.getOutputStream();
81 ImageIO.write(buffImg, "jpeg", sos);
82 sos.close();
83
84 }