java驗證碼產生具體代碼_java

來源:互聯網
上載者:User

本文執行個體為大家分享了java驗證碼產生的範例程式碼,供大家參考,具體內容如下

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;            // 定義圖片的width  private int           height       = DEFAULT_HEIGHT;            // 定義圖片的height  private int           length       = DEFAULT_CODE_LEN;           // 定義圖片上顯示驗證碼的個數  private int           xx         = DEFAULT_CODE_X;            // 定義圖片上顯示驗證碼x座標  private int           yy         = DEFAULT_CODE_Y;            // 定義圖片上顯示驗證碼y座標  private int           fontSize      = DEFAULT_FONT_SIZE;          // 定義圖片上顯示驗證碼的字型大小  private String         fontFamily     = DEFAULT_FONT_FAMILY;         // 定義圖片上顯示驗證碼的個數   private CaptchaFactory() {  }   public static CaptchaFactory getInstance() {    return instance;  }   /**   * 配置寬高   *   * @param w   * @param h   * @return   */  public CaptchaFactory configWidthAndHeight(int w, int h) {    instance.width = w;    instance.height = h;    return instance;  }   /**   * 配置座標   *   * @param x   * @param y   * @return   */  public CaptchaFactory configXY(int x, int y) {    instance.xx = x;    instance.yy = y;    return instance;  }   /**   * 配置字型大小   *   * @param fontSize   * @return   */  public CaptchaFactory configFontSize(int fontSize) {    instance.fontSize = fontSize;    return instance;  }   /**   * 配置字型   *   * @param fontFamily   * @return   */  public CaptchaFactory configFontSize(String fontFamily) {    instance.fontFamily = fontFamily;    return instance;  }   public void write(HttpServletRequest request, HttpServletResponse response) throws IOException {    // 將四位元字的驗證碼儲存到Session中。    Map captcha = generate();    String randomCode = (String) captcha.get("captchaCode");    BufferedImage buffImg = (BufferedImage) captcha.get("captchaImg");     HttpSession session = request.getSession();    session.setAttribute("code", randomCode);     // 禁止映像緩衝。    response.setHeader("Pragma", "no-cache");    response.setHeader("Cache-Control", "no-cache");    response.setDateHeader("Expires", 0);    response.setContentType("image/jpeg");     // 將映像輸出到Servlet輸出資料流中。    ServletOutputStream outputStream = response.getOutputStream();    ImageIO.write(buffImg, "jpeg", outputStream);    outputStream.close();  }   public Map<String, Object> generate() throws IOException {    // 定義映像buffer    BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);    Graphics gd = buffImg.getGraphics();    // 設定背景色    gd.setColor(getRandColor(200, 250));    gd.fillRect(0, 0, width, height);    // 設定字型,字型的大小應該根據圖片的高度來定。    gd.setFont(new Font(fontFamily, Font.PLAIN, fontSize));     // 建立一個隨機數產生器類    Random random = new Random();     // 隨機產生40條幹擾線,使圖象中的認證碼不易被其它程式探測到。    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用於儲存隨機產生的驗證碼,以便使用者登入後進行驗證。    StringBuffer randomCode = new StringBuffer();    int red = 0, green = 0, blue = 0;     // 隨機產生 length 個驗證碼。    for (int i = 0; i < length; i++) {      // 得到隨機產生的驗證碼數字。      String code = String.valueOf(CODE_SEQUENCE[random.nextInt(36)]);      // 產生隨機的顏色分量來構造顏色值,這樣輸出的每位元字的顏色值都將不同。      red = random.nextInt(110);      green = random.nextInt(110);      blue = random.nextInt(110);       // 用隨機產生的顏色將驗證碼繪製到映像中。      gd.setColor(new Color(red + 20, green + 20, blue + 20));      gd.drawString(code, i * xx + 6, yy);       // 將產生的隨機數組合在一起。      randomCode.append(code);    }    Map<String, Object> retval = new HashMap<>();    retval.put("captchaCode", randomCode.toString());    retval.put("captchaImg", buffImg);    return retval;  }   /**   * 給定範圍獲得隨機顏色   *   * @param fc   *      最小值   * @param bc   *      最大值   * @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);  }}

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.