最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java生成驗證碼功能實例代碼

 更新時間:2017年05月25日 13:59:27   作者:無意有請  
頁面上輸入驗證碼是比較常見的一個功能,實現(xiàn)起來也很簡單.給大家寫一個簡單的生成驗證碼的示例程序,需要的朋友可以借鑒一下

頁面上輸入驗證碼是比較常見的一個功能,實現(xiàn)起來也很簡單.給大家寫一個簡單的生成驗證碼的示例程序,需要的朋友可以借鑒一下.

閑話少續(xù),直接上代碼.代碼中的注釋很詳細(xì).

package com.SM_test.utils; 
import java.awt.Color;  
import java.awt.Font;  
import java.awt.Graphics;  
import java.awt.Graphics2D;  
import java.awt.RenderingHints;  
import java.awt.geom.AffineTransform;  
import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
import java.util.Arrays;  
import java.util.Random;  
import javax.imageio.ImageIO;  
public class VerifyCodeUtils{  
  //使用到Algerian字體,系統(tǒng)里沒有的話需要安裝字體,字體只顯示大寫,去掉了1,0,i,o幾個容易混淆的字符  
  public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";  
  private static Random random = new Random();  
  /** 
   * 使用系統(tǒng)默認(rèn)字符源生成驗證碼 
   * @param verifySize  驗證碼長度 
   * @return 
   */  
  public static String generateVerifyCode(int verifySize){  
    return generateVerifyCode(verifySize, VERIFY_CODES);  
  }  
  /** 
   * 使用指定源生成驗證碼 
   * @param verifySize  驗證碼長度 
   * @param sources  驗證碼字符源 
   * @return 
   */  
  public static String generateVerifyCode(int verifySize, String sources){  
    if(sources == null || sources.length() == 0){  
      sources = VERIFY_CODES;  
    }  
    int codesLen = sources.length();  
    Random rand = new Random(System.currentTimeMillis());  
    StringBuilder verifyCode = new StringBuilder(verifySize);  
    for(int i = 0; i < verifySize; i++){  
      verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));  
    }  
    return verifyCode.toString();  
  }  
  /** 
   * 生成隨機(jī)驗證碼文件,并返回驗證碼值 
   * @param w 
   * @param h 
   * @param outputFile 
   * @param verifySize 
   * @return 
   * @throws IOException 
   */  
  public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{  
    String verifyCode = generateVerifyCode(verifySize);  
    outputImage(w, h, outputFile, verifyCode);  
    return verifyCode;  
  }  
  /** 
   * 輸出隨機(jī)驗證碼圖片流,并返回驗證碼值 
   * @param w 
   * @param h 
   * @param os 
   * @param verifySize 
   * @return 
   * @throws IOException 
   */  
  public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{  
    String verifyCode = generateVerifyCode(verifySize);  
    outputImage(w, h, os, verifyCode);  
    return verifyCode;  
  }  
  /** 
   * 生成指定驗證碼圖像文件 
   * @param w 
   * @param h 
   * @param outputFile 
   * @param code 
   * @throws IOException 
   */  
  public static void outputImage(int w, int h, File outputFile, String code) throws IOException{  
    if(outputFile == null){  
      return;  
    }  
    File dir = outputFile.getParentFile();  
    if(!dir.exists()){  
      dir.mkdirs();  
    }  
    try{  
      outputFile.createNewFile();  
      FileOutputStream fos = new FileOutputStream(outputFile);  
      outputImage(w, h, fos, code);  
      fos.close();  
    } catch(IOException e){  
      throw e;  
    }  
  }  
  /** 
   * 輸出指定驗證碼圖片流 
   * @param w 
   * @param h 
   * @param os 
   * @param code 
   * @throws IOException 
   */  
  public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{  
    int verifySize = code.length();  
    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);  
    Random rand = new Random();  
    Graphics2D g2 = image.createGraphics();  
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);  
    Color[] colors = new Color[5];  
    Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,  
        Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,  
        Color.PINK, Color.YELLOW };  
    float[] fractions = new float[colors.length];  
    for(int i = 0; i < colors.length; i++){  
      colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];  
      fractions[i] = rand.nextFloat();  
    }  
    Arrays.sort(fractions);  
    g2.setColor(Color.GRAY);// 設(shè)置邊框色  
    g2.fillRect(0, 0, w, h);  
    Color c = getRandColor(200, 255);  
    g2.setColor(c);// 設(shè)置背景色  
    g2.fillRect(0, 2, w, h-4);  
    //繪制干擾線  
    Random random = new Random();  
    g2.setColor(getRandColor(50, 255));// 設(shè)置線條的顏色  
    for (int i = 0; i < 20; i++) {  
      int x = random.nextInt(w - 1);  
      int y = random.nextInt(h - 1);  
      int xl = random.nextInt(6) + 1;  
      int yl = random.nextInt(12) + 1;  
      g2.drawLine(x, y, x + xl + 40, y + yl + 20);  
    }  
    // 添加噪點  
    float yawpRate = 0.05f;// 噪聲率  
    int area = (int) (yawpRate * w * h);  
    for (int i = 0; i < area; i++) {  
      int x = random.nextInt(w);  
      int y = random.nextInt(h);  
      int rgb = getRandomIntColor();  
      image.setRGB(x, y, rgb);  
    }  
    shear(g2, w, h, c);// 使圖片扭曲  
//    g2.setColor(getRandColor(100, 160));  
    int fontSize = h-4;  
    Font font = new Font("Algerian", Font.ITALIC, fontSize);  
    g2.setFont(font);  
    char[] chars = code.toCharArray();  
    for(int i = 0; i < verifySize; i++){  
      AffineTransform affine = new AffineTransform();  
      affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);  
      g2.setTransform(affine); 
      g2.setColor(getRandColor(100, 160)); 
      g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h-(h - (int)(fontSize*0.75))/2);  
    }  
    g2.dispose();  
    ImageIO.write(image, "jpg", os);  
  }  
  private static Color getRandColor(int fc, int bc) {  
    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);  
  }  
  private static int getRandomIntColor() {  
    int[] rgb = getRandomRgb();  
    int color = 0;  
    for (int c : rgb) {  
      color = color << 8;  
      color = color | c;  
    }  
    return color;  
  }  
  private static int[] getRandomRgb() {  
    int[] rgb = new int[3];  
    for (int i = 0; i < 3; i++) {  
      rgb[i] = random.nextInt(255);  
    }  
    return rgb;  
  }  
  private static void shear(Graphics g, int w1, int h1, Color color) {  
    shearX(g, w1, h1, color);  
    shearY(g, w1, h1, color);  
  }  
  private static void shearX(Graphics g, int w1, int h1, Color color) {  
    int period = random.nextInt(2);  
    boolean borderGap = true;  
    int frames = 1;  
    int phase = random.nextInt(2);  
    for (int i = 0; i < h1; i++) {  
      double d = (double) (period >> 1)  
          * Math.sin((double) i / (double) period  
              + (6.2831853071795862D * (double) phase)  
              / (double) frames);  
      g.copyArea(0, i, w1, 1, (int) d, 0);  
      if (borderGap) {  
        g.setColor(color);  
        g.drawLine((int) d, i, 0, i);  
        g.drawLine((int) d + w1, i, w1, i);  
      }  
    }  
  }  
  private static void shearY(Graphics g, int w1, int h1, Color color) {  
    int period = random.nextInt(40) + 10; // 50;  
    boolean borderGap = true;  
    int frames = 20;  
    int phase = 7;  
    for (int i = 0; i < w1; i++) {  
      double d = (double) (period >> 1)  
          * Math.sin((double) i / (double) period  
              + (6.2831853071795862D * (double) phase)  
              / (double) frames);  
      g.copyArea(i, 0, 1, h1, 0, (int) d);  
      if (borderGap) {  
        g.setColor(color);  
        g.drawLine(i, (int) d, i, 0);  
        g.drawLine(i, (int) d + h1, i, h1);  
      }  
    }  
  }  
  public static void main(String[] args) throws IOException{  
    File dir = new File("e:/abc");  
    int w = 200, h = 80;  
    for(int i = 0; i < 50; i++){  
      String verifyCode = generateVerifyCode(4);  
      File file = new File(dir, verifyCode + ".jpg");  
      outputImage(w, h, file, verifyCode);  
    }  
  }  
}  

上面這段代碼就能生成一個驗證碼,略微修改就能生成各種各樣的形式,main方法可以測試.

下面為大家寫一下如何返回到頁面

package com.SM_test.saomiao.constroller; 
import java.io.IOException; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import com.SM_test.utils.VerifyCodeUtils; 
@Controller  
public class IndexConstroller { 
  @RequestMapping(value = "/index") 
  public void index(HttpServletRequest request,HttpServletResponse response) throws IOException{ 
    response.setHeader("Pragma", "No-cache");  
    response.setHeader("Cache-Control", "no-cache");  
    response.setDateHeader("Expires", 0);  
    response.setContentType("image/jpeg");  
    //生成隨機(jī)字串  
    String verifyCode = VerifyCodeUtils.generateVerifyCode(4);  
    //存入會話session  
    HttpSession session = request.getSession(true);  
    session.setAttribute("rand", verifyCode.toLowerCase());  
    //生成圖片  
    int w = 200, h = 80;  
    VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);  
  } 
} 

很簡單,用HttpServletResponse 就OK了.

需要顯示驗證碼的地方可以直接用img標(biāo)簽,地址就是該Controller的URL就OK了

以上所述是小編給大家介紹的Java生成驗證碼功能實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • 五分鐘帶你快速學(xué)習(xí)Spring?IOC

    五分鐘帶你快速學(xué)習(xí)Spring?IOC

    這篇文章主要給大家介紹了關(guān)于如何通過五分鐘快速學(xué)習(xí)Spring?IOC的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2022-03-03
  • MyBatis攔截器的實現(xiàn)原理

    MyBatis攔截器的實現(xiàn)原理

    這篇文章主要介紹了MyBatis攔截器的實現(xiàn)原理,Mybatis攔截器并不是每個對象里面的方法都可以被攔截的,其具體內(nèi)容感興趣的小伙伴課題參考一下下面文章內(nèi)容
    2022-08-08
  • Java實現(xiàn)簡易的分詞器功能

    Java實現(xiàn)簡易的分詞器功能

    搜索功能是具備數(shù)據(jù)庫功能的系統(tǒng)的一大重要特性和功能,生活中常見的搜索功能基本上都具備了分詞搜索功能.然而ES功能固然強(qiáng)大,但對于學(xué)生或小項目而言整合起來太費人力物力,若是寫個分詞器就會使項目錦上添花,使其不僅僅是只能單關(guān)鍵詞搜索的系統(tǒng),需要的朋友可以參考下
    2021-06-06
  • java基礎(chǔ)的詳細(xì)了解第五天

    java基礎(chǔ)的詳細(xì)了解第五天

    這篇文章對Java編程語言的基礎(chǔ)知識作了一個較為全面的匯總,在這里給大家分享一下。需要的朋友可以參考,希望能給你帶來幫助
    2021-08-08
  • Java如何執(zhí)行cmd命令

    Java如何執(zhí)行cmd命令

    這篇文章主要介紹了Java如何執(zhí)行cmd命令問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • Java中Getter和Setter方法及主要區(qū)別

    Java中Getter和Setter方法及主要區(qū)別

    這篇文章主要給大家介紹了關(guān)于Java中Getter和Setter方法及主要區(qū)別的相關(guān)資料,getter和setter方法是用于封裝類中的私有屬性的方法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-04-04
  • Java利用跳躍表解決雙重隊列問題詳解

    Java利用跳躍表解決雙重隊列問題詳解

    這篇文章主要為大家詳細(xì)介紹了Java如何利用跳躍表來解決雙重隊列的問題。本文通過一個簡單的例題進(jìn)行了講解,感興趣的小伙伴可以了解一下
    2022-12-12
  • Java字符串split使用方法代碼實例

    Java字符串split使用方法代碼實例

    這篇文章主要介紹了Java字符串split使用方法代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • eclipse輸出Hello World的實現(xiàn)方法

    eclipse輸出Hello World的實現(xiàn)方法

    這篇文章主要介紹了eclipse輸出Hello World的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • 詳解springboot + profile(不同環(huán)境讀取不同配置)

    詳解springboot + profile(不同環(huán)境讀取不同配置)

    本篇文章主要介紹了springboot + profile(不同環(huán)境讀取不同配置),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-05-05

最新評論

峡江县| 岳普湖县| 邳州市| 讷河市| 河东区| 大新县| 中牟县| 东丰县| 马鞍山市| 道孚县| 乌拉特中旗| 祁门县| 新兴县| 乾安县| 绍兴县| 吉隆县| 长春市| 泗阳县| 休宁县| 南京市| 巴林右旗| 聂拉木县| 普兰县| 蒙自县| 彭州市| 古丈县| 荥阳市| 杭锦后旗| 健康| 和顺县| 玛多县| 黔西| 沈阳市| 乌兰县| 綦江县| 仙桃市| 宜宾县| 黄浦区| 刚察县| 海晏县| 新化县|