The java captcha generates the concrete code

  • 2020-05-09 18:39:46
  • OfStack

For your reference, the example code generated by java verification code is Shared as an example in this article. The details are as follows


package com.gonvan.component.captcha;
 
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
 
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
/**
 * Created by yuerzm on 2016/3/14.
 */
public class CaptchaFactory {
 
  private static final char[]   CODE_SEQUENCE    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    .toCharArray();
  private static final int    DEFAULT_WIDTH    = 60;
  private static final int    DEFAULT_HEIGHT   = 20;
  private static final int    DEFAULT_CODE_LEN  = 4;
  private static final int    DEFAULT_CODE_X   = 13;
  private static final int    DEFAULT_CODE_Y   = 16;
  private static final int    DEFAULT_FONT_SIZE  = 18;
  private static final String   DEFAULT_FONT_FAMILY = "Times New Roman";
  private static CaptchaFactory  instance      = new CaptchaFactory();
  private int           width        = DEFAULT_WIDTH;            //  picture-defining width
  private int           height       = DEFAULT_HEIGHT;            //  picture-defining height
  private int           length       = DEFAULT_CODE_LEN;           //  Define the number of captchas to display on the image 
  private int           xx         = DEFAULT_CODE_X;            //  Define the captcha displayed on the image x coordinates 
  private int           yy         = DEFAULT_CODE_Y;            //  Define the captcha displayed on the image y coordinates 
  private int           fontSize      = DEFAULT_FONT_SIZE;          //  Define the font size to display the captcha on the image 
  private String         fontFamily     = DEFAULT_FONT_FAMILY;         //  Define the number of captchas to display on the image 
 
  private CaptchaFactory() {
  }
 
  public static CaptchaFactory getInstance() {
    return instance;
  }
 
  /**
   *  Configure wide high 
   *
   * @param w
   * @param h
   * @return
   */
  public CaptchaFactory configWidthAndHeight(int w, int h) {
    instance.width = w;
    instance.height = h;
    return instance;
  }
 
  /**
   *  Configuration coordinates 
   *
   * @param x
   * @param y
   * @return
   */
  public CaptchaFactory configXY(int x, int y) {
    instance.xx = x;
    instance.yy = y;
    return instance;
  }
 
  /**
   *  Configure font size 
   *
   * @param fontSize
   * @return
   */
  public CaptchaFactory configFontSize(int fontSize) {
    instance.fontSize = fontSize;
    return instance;
  }
 
  /**
   *  Configure the font 
   *
   * @param fontFamily
   * @return
   */
  public CaptchaFactory configFontSize(String fontFamily) {
    instance.fontFamily = fontFamily;
    return instance;
  }
 
  public void write(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //  will 4 The numeric captcha is saved to Session In the. 
    Map captcha = generate();
    String randomCode = (String) captcha.get("captchaCode");
    BufferedImage buffImg = (BufferedImage) captcha.get("captchaImg");
 
    HttpSession session = request.getSession();
    session.setAttribute("code", randomCode);
 
    //  Disable image caching. 
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");
 
    //  Output the image to Servlet In the output stream. 
    ServletOutputStream outputStream = response.getOutputStream();
    ImageIO.write(buffImg, "jpeg", outputStream);
    outputStream.close();
  }
 
  public Map<String, Object> generate() throws IOException {
    //  Define the image buffer
    BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics gd = buffImg.getGraphics();
    //  Setting the background color 
    gd.setColor(getRandColor(200, 250));
    gd.fillRect(0, 0, width, height);
    //  Set the font size according to the height of the image. 
    gd.setFont(new Font(fontFamily, Font.PLAIN, fontSize));
 
    //  create 1 Random number generator class 
    Random random = new Random();
 
    //  Randomly generated 40 Interference line, so that the authentication code in the image is not easily detected by other programs. 
    gd.setColor(getRandColor(160, 200));
    for (int i = 0; i < 155; 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  length  Captcha. 
    for (int i = 0; i < length; i++) {
      //  Get the randomly generated captcha number. 
      String code = String.valueOf(CODE_SEQUENCE[random.nextInt(36)]);
      //  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(110);
      green = random.nextInt(110);
      blue = random.nextInt(110);
 
      //  Draws the captcha into the image with randomly generated colors. 
      gd.setColor(new Color(red + 20, green + 20, blue + 20));
      gd.drawString(code, i * xx + 6, yy);
 
      //  Combine the generated random Numbers in 1 Up. 
      randomCode.append(code);
    }
    Map<String, Object> retval = new HashMap<>();
    retval.put("captchaCode", randomCode.toString());
    retval.put("captchaImg", buffImg);
    return retval;
  }
 
  /**
   *  Get a random color for a given range 
   *
   * @param fc
   *       The minimum value 
   * @param bc
   *       The maximum 
   * @return Color
   */
  private Color getRandColor(int fc, int bc) {
    Random random = new Random();
    if (fc > 255)
      fc = 255;
    if (bc > 255)
      bc = 255;
    int r = fc + random.nextInt(bc - fc);
    int g = fc + random.nextInt(bc - fc);
    int b = fc + random.nextInt(bc - fc);
    return new Color(r, g, b);
  }
}

The above is the entire content of this article, I hope to help you with your study.


Related articles: