albertchendao
10/21/2018 - 9:13 AM

Java 生成验证码

@RequestMapping({"/code"})
  public void verifyCode(HttpServletResponse response, HttpServletRequest request)
  {
    response.setContentType("image/jpeg");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0L);
    HttpSession session = request.getSession();
    
    int width = 60;int height = 18;
    BufferedImage image = new BufferedImage(width, height, 1);
    
    Graphics g = image.getGraphics();
    
    g.setColor(new Color(16777215));
    g.fillRect(0, 0, width, height);
    String[] mapTable = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
    StringBuffer rands = new StringBuffer();
    Random ran = new Random();
    for (int i = 0; i < 4; i++) {
      rands.append(mapTable[ran.nextInt(mapTable.length)]);
    }
    String rand = rands.toString();
    
    session.setAttribute("rand", rand);
    
    g.setColor(Color.black);
    g.setFont(new Font("Times New Roman", 1, 16));
    String Str = rand.substring(0, 1);
    g.drawString(Str, 6, 12);
    Str = rand.substring(1, 2);
    g.drawString(Str, 19, 17);
    Str = rand.substring(2, 3);
    g.drawString(Str, 32, 15);
    Str = rand.substring(3, 4);
    g.drawString(Str, 45, 15);
    
    Random random = new Random();
    for (int i = 0; i < 3; i++)
    {
      Color c5 = new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200));
      g.setColor(c5);
      int x = random.nextInt(width / 2);
      int y = random.nextInt(height / 2);
      int xl = random.nextInt(60);
      int yl = random.nextInt(20);
      g.drawLine(x, y, x + xl, y + yl);
    }
    for (int i = 0; i < 68; i++)
    {
      Color c6 = new Color(random.nextInt(250), random.nextInt(250), random.nextInt(200));
      g.setColor(c6);
      int x = random.nextInt(width);
      int y = random.nextInt(height);
      g.drawOval(x, y, 0, 0);
    }
    g.dispose();
    try
    {
      ServletOutputStream responseOutputStream = response.getOutputStream();
      
      ImageIO.write(image, "JPEG", responseOutputStream);
      
      responseOutputStream.flush();
      responseOutputStream.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    image = null;
  }