java generates the image captcha instance code

  • 2020-05-09 18:35:13
  • OfStack

The article about the image verification code of java has been updated recently, which helps you to master the generation technology of java verification code. The following is the easiest way to generate the image verification code of java for your reference.

Now that all industries are customizing their systems with machine registration in mind, the most efficient way to do this is input validation. There are many ways to verify:

1. Question validation, which is also picture validation, generates the question on the picture, and then enters the answer in the input box.

2. Picture verification, enter the text information displayed on the picture.

3. SMS verification, more complex, users do not like it.

4. There is also the latest verification method of baidu. Generate text on the image, then a text click box appears, select the text you see on the validation image.
Now share 1 of the code that java generates the captcha, which is a basic piece of code. It can be used directly in learning, and you can add your own logical validation if you need more complex validation.


@Controller
public class ImgVerifyCode extends HttpServlet {
 
  /**
   *
   */
  private static final long serialVersionUID = 1L;
 
  /**
   *  The width of the captcha image. 
   */
  private int width = 70;
 
  /**
   *  Captcha image height. 
   */
  private int height =30;
 
  /**
   *  Number of verification code characters 
   */
  private int codeCount = 5;
 
  /**
   * xx
   */
  private int xx = 0;
 
  /**
   *  The font height 
   */
  private int fontHeight;
 
  /**
   * codeY
   */
  private int codeY;
 
  /**
   * codeSequence
   */
   String[] codeSequence = { "1" , "2" , "3" , "4" , "5" ,"6","7","8","9","A","a","B","b","c","C"
       ,"D","d","E","e","F","f","G","g","z","X","Q","v"};
 
  /**
   *  Initializes the validation image properties 
   */
  public void init() throws ServletException {
    //  from web.xml Get the initial information in 
    //  The width of the 
    String strWidth =width+"";
    //  highly 
    String strHeight = height+"";
    //  The number of characters 
    String strCodeCount = codeCount+"";
 
    //  Converts configuration information to numeric values 
    try {
      if (strWidth != null && strWidth.length() != 0) {
        width = Integer.parseInt(strWidth);
      }
      if (strHeight != null && strHeight.length() != 0) {
        height = Integer.parseInt(strHeight);
      }
      if (strCodeCount != null && strCodeCount.length() != 0) {
        codeCount = Integer.parseInt(strCodeCount);
      }
    } catch (NumberFormatException e) {
      e.printStackTrace();
    }
 
    xx = width / (codeCount + 2); // Generates the horizontal distance of the random number 
    fontHeight = height - 12;   // The height of a number to generate a random number 
    codeY = height - 8;      // Generate the vertical distance of the random number 
 
  }
 
 
  protected String images(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException,IOException {
    init();
    //  Define the image buffer
    BufferedImage buffImg = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_RGB);
    Graphics2D gd = buffImg.createGraphics();
 
    //  create 1 Random number generator class 
    Random random = new Random();
 
    //  Fill the image with white 
    gd.setColor(Color.WHITE);
    gd.fillRect(0, 0, width, height);
 
    //  Create a font. The size of the font should depend on the height of the image. 
    Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
    //  Set the font. 
    gd.setFont(font);
 
    //  Picture frame. 
    gd.setColor(Color.BLACK);
    gd.drawRect(0, 0, width - 1, height - 1);
 
    //  Randomly generated 4 Interference line, so that the authentication code in the image is not easily detected by other programs. 
    gd.setColor(Color.BLACK);
    for (int i = 0; i < 4; i++) {
      int x = random.nextInt(width);
      int y = random.nextInt(height);
      int xl = random.nextInt(12);
      int yl = random.nextInt(12);
      gd.drawLine(x, y, x + xl, y + yl);
    }
 
    // randomCode Used to save the randomly generated captcha for user authentication after login. 
    StringBuffer randomCode = new StringBuffer();
    int red = 0, green = 0, blue = 0;
 
    //  Randomly generated codeCount Number verification code. 
    for (int i = 0; i < codeCount; i++) {
      //  Get the randomly generated captcha number. 
      String strRand = String.valueOf(codeSequence[random.nextInt(27)]);
      //  Generate a random color component to construct a color value, so that the color value of each number output will be different. 
      red = random.nextInt(125);
      green = random.nextInt(255);
      blue = random.nextInt(200);
 
      //  Draws the captcha into the image with randomly generated colors. 
      gd.setColor(new Color(red, green, blue));
      gd.drawString(strRand, (i + 1) * xx, codeY);
 
      //  Will produce the 4 I'm going to have a bunch of random Numbers 1 Up. 
      randomCode.append(strRand);
    }
    //  will 4 The numeric captcha is saved to Session In the. 
    HttpSession session = req.getSession();
    session.setAttribute("validateCode", randomCode.toString());
 
    //  Disable image caching. 
    resp.setHeader("Pragma", "no-cache");
    resp.setHeader("Cache-Control", "no-cache");
    resp.setDateHeader("Expires", 0);
 
    resp.setContentType("image/jpeg");
 
    //  Output the image to Servlet In the output stream. 
    ServletOutputStream sos = resp.getOutputStream();
    ImageIO.write(buffImg, "jpeg", sos);
    sos.close();
    return null;
  }
   } 

This code is the basic method for generating validation images.

Above is the whole content of this article, hope to help you to learn, you can also check the previous article for in-depth study.


Related articles: