验证码(一)

验证码(一)

 1 @RequestMapping("/image")
 2     public void image(HttpServletRequest request, HttpServletResponse response) throws IOException {
 3         request.setCharacterEncoding("utf-8");
 4 
 5         BufferedImage bfi = new BufferedImage(80, 25, BufferedImage.TYPE_INT_RGB);
 6         Graphics g = bfi.getGraphics();
 7         g.fillRect(0, 0, 80, 25);
 8 
 9         //验证码字符范围
10         char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
11         Random r = new Random();
12         int index;
13         StringBuffer sb = new StringBuffer(); //保存字符串
14         for (int i = 0; i < 4; i++) {
15             index = r.nextInt(ch.length);
16             g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
17             Font font = new Font("宋体", 30, 20);
18             g.setFont(font);
19             g.drawString(ch[index] + "", (i * 20) + 2, 23);
20             sb.append(ch[index]);
21         }
22 
23         // 添加噪点
24         int area = (int) (0.02 * 60 * 25);
25         for (int i = 0; i < area; ++i) {
26             int x = (int) (Math.random() * 80);
27             int y = (int) (Math.random() * 25);
28             bfi.setRGB(x, y, (int) (Math.random() * 255));
29         }
30 
31         //设置验证码中的干扰线
32         for (int i = 0; i < 3; i++) {
33             //随机获取干扰线的起点和终点
34             int xstart = (int) (Math.random() * 80);
35             int ystart = (int) (Math.random() * 25);
36             int xend = (int) (Math.random() * 80);
37             int yend = (int) (Math.random() * 25);
38             g.setColor(interLine(1, 255));
39             g.drawLine(xstart, ystart, xend, yend);
40         }
41         HttpSession session = request.getSession();  //保存到session
42         session.setAttribute("verificationCode", sb.toString());
43         ImageIO.write(bfi, "JPG", response.getOutputStream());  //写到输出流
44     }
45 
46     private static Color interLine(int Low, int High) {
47         if (Low > 255)
48             Low = 255;
49         if (High > 255)
50             High = 255;
51         if (Low < 0)
52             Low = 0;
53         if (High < 0)
54             High = 0;
55         int interval = High - Low;
56         int r = Low + (int) (Math.random() * interval);
57         int g = Low + (int) (Math.random() * interval);
58         int b = Low + (int) (Math.random() * interval);
59         return new Color(r, g, b);
60     }
61 
62     @RequestMapping("/checkCode")
63     @ResponseBody
64     public Map<String,Object> checkCode(String code,HttpSession session){
65         Map<String,Object> map=new HashMap<>();
66 
67         String verificationCode = (String) session.getAttribute("verificationCode");
68         if(verificationCode.equalsIgnoreCase(code)){
69             map.put("valid",true);
70         }else{
71             map.put("valid",false);
72         }
73         return map;
74     }

 

posted @ 2019-05-15 17:16  司徒二条  阅读(263)  评论(0编辑  收藏  举报