在servlet上实现 生成验证码图片 功能

忘是亡心i 2024-03-17 10:37 91阅读 0赞

在servlet上实现 生成验证码图片 功能

代码:

  1. package com.dong.servlet;
  2. /**
  3. * 生成验证码图片
  4. */
  5. import javax.imageio.ImageIO;
  6. import javax.servlet.*;
  7. import javax.servlet.http.*;
  8. import javax.servlet.annotation.*;
  9. import java.awt.*;
  10. import java.awt.image.BufferedImage;
  11. import java.io.IOException;
  12. import java.util.Random;
  13. @WebServlet("/CodeServlet")
  14. public class CodeServlet extends HttpServlet {
  15. private static final long serialVersionUID = 1L;
  16. public CodeServlet() {
  17. }
  18. @Override
  19. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  20. this.doPost(request,response);
  21. }
  22. @Override
  23. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  24. //设置字符集
  25. request.setCharacterEncoding("UTF-8");
  26. BufferedImage bufferedImage=new BufferedImage(80,25,BufferedImage.TYPE_INT_RGB);
  27. Graphics graphics=bufferedImage.getGraphics();
  28. graphics.fillRect(0,0,80,25);
  29. //验证码字符范围
  30. char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
  31. Random random=new Random();
  32. int index;
  33. StringBuffer stringBuffer=new StringBuffer();// 保存字符串
  34. for(int i=0;i<4;i++){
  35. index=random.nextInt(ch.length);
  36. graphics.setColor(new Color(random.nextInt(225),random.nextInt(225),random.nextInt(225)));
  37. Font font=new Font("宋体",30,20);
  38. graphics.setFont(font);
  39. graphics.drawString(ch[index]+"",(i*20)+2,23);
  40. stringBuffer.append(ch[index]);
  41. }
  42. // 设置验证码中的干扰线
  43. for (int i=0;i<6;i++){
  44. // 随机获取干扰线的起点和终点
  45. int xStart=(int) (Math.random()*80);
  46. int yStart=(int) (Math.random()*25);
  47. int xEnd=(int) (Math.random()*80);
  48. int yEnd=(int) (Math.random()*25);
  49. graphics.getColor();
  50. graphics.drawLine(xStart,yStart,xEnd,yEnd);
  51. }
  52. HttpSession httpSession=request.getSession();// 保存到session
  53. httpSession.setAttribute("code",stringBuffer.toString());
  54. ImageIO.write(bufferedImage,"JPG",response.getOutputStream());// 写到输出流
  55. }
  56. private static Color interLine(int Low, int High){
  57. if (Low>225)
  58. Low=225;
  59. if (High > 255)
  60. High = 255;
  61. if (Low < 0)
  62. Low = 0;
  63. if (High < 0)
  64. High = 0;
  65. int interval=High-Low;
  66. int r=Low+(int) (Math.random()*interval);
  67. int g=Low+(int) (Math.random()*interval);
  68. int b=Low+(int) (Math.random()*interval);
  69. return new Color(r,g,b);
  70. }
  71. }

在浏览器上运行结果:

3864f20dafd34f01aa0e34096c98be1f.png

发表评论

表情:
评论列表 (有 0 条评论,91人围观)

还没有评论,来说两句吧...

相关阅读