验证码
程序员文章站
2022-02-11 06:28:36
...
1. <%@ page contentType="image/jpeg" import="java.awt.*,
2. java.awt.image.*,java.util.*,javax.imageio.*" %>
3. <%
4. // 在内存中创建图象
5. int width=60, height=20;
6. BufferedImage image = new BufferedImage(width, height,
7. BufferedImage.TYPE_INT_RGB);
8.
9. // 获取图形上下文
10. Graphics g = image.getGraphics();
11.
12. // 设定背景色
13. g.setColor(new Color(0xDCDCDC));
14. g.fillRect(0, 0, width, height);
15.
16. //画边框
17. g.setColor(Color.black);
18. g.drawRect(0,0,width-1,height-1);
19.
20. // 取随机产生的认证码(4位数字)
21. String rand = request.getParameter("rand");
22. rand = rand.substring(0,rand.indexOf("."));
23. switch(rand.length())
24. {
25. case 1: rand = "000"+rand; break;
26. case 2: rand = "00"+rand; break;
27. case 3: rand = "0"+rand; break;
28. default: rand = rand.substring(0,4); break;
29. }
30.
31. // 将认证码存入SESSION
32. session.setAttribute("rand",rand);
33.
34. // 将认证码显示到图象中
35. g.setColor(Color.black);
36. Integer tempNumber = new Integer(rand);
37. String numberStr = tempNumber.toString();
38.
39. g.setFont(new Font("Atlantic Inline",Font.PLAIN,18));
40. String Str = numberStr.substring(0,1);
41. g.drawString(Str,8,17);
42.
43. Str = numberStr.substring(1,2);
44. g.drawString(Str,20,15);
45. Str = numberStr.substring(2,3);
46. g.drawString(Str,35,18);
47.
48. Str = numberStr.substring(3,4);
49. g.drawString(Str,45,15);
50.
51. // 随机产生88个干扰点,使图象中的认证码不易被其它程序探测到
52. Random random = new Random();
53. for (int i=0;i<20;i++)
54. {
55. int x = random.nextInt(width);
56. int y = random.nextInt(height);
57. g.drawOval(x,y,0,0);
58. }
59.
60. // 图象生效
61. g.dispose();
62.
63. // 输出图象到页面
64. ImageIO.write(image, "JPEG", response.getOutputStream());
65. %>