> Java > java지도 시간 > 본문

Java 기반 인증 코드 생성 기능 예제 튜토리얼

零下一度
풀어 주다: 2017-05-27 09:35:13
원래의
1546명이 탐색했습니다.

페이지에 인증 코드를 입력하는 것은 비교적 일반적인 기능이며 구현도 매우 간단합니다. 인증 코드가 필요한 친구는

인증 입력을 통해 배울 수 있습니다.

페이지의 코드 코드는 비교적 일반적인 기능이며 구현하기가 매우 간단합니다. 인증 코드가 필요한 친구는 이를 통해 배울 수 있습니다. 더 나아가 코드로 직접 가보겠습니다. 주석은 매우 상세합니다.

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字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符  
  public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";  
  private static Random random = new Random();  
  /** 
   * 使用系统默认字符源生成验证码 
   * @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();  
  }  
  /** 
   * 生成随机验证码文件,并返回验证码值 
   * @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;  
  }  
  /** 
   * 输出随机验证码图片流,并返回验证码值 
   * @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);// 设置边框色  
    g2.fillRect(0, 0, w, h);  
    Color c = getRandColor(200, 255);  
    g2.setColor(c);// 设置背景色  
    g2.fillRect(0, 2, w, h-4);  
    //绘制干扰线  
    Random random = new Random();  
    g2.setColor(getRandColor(50, 255));// 设置线条的颜色  
    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);  
    }  
  }  
}
로그인 후 복사

위 코드는 약간만 수정하면 다양한 형태의 인증 코드를 생성할 수 있습니다. 테스트를 거쳤습니다.

다음은 모든 사람을 위해 작성되었습니다.

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");  
    //生成随机字串  
    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);  
  } 
}
로그인 후 복사

페이지로 돌아가는 방법은 매우 간단합니다.

확인 코드를 표시해야 하는 모든 곳에

img 태그

를 직접 사용할 수 있으며, 주소는 컨트롤러의 주소입니다. URL은 괜찮습니다[관련 추천]

상세 분석 Java를 이용한 인증코드 생성 방법

2.

JavaScript를 이용한 인증 구현 코드 기능 예시

기능 예시 코드 Python으로 검증 코드 구현하기

4.

[php 검증 코드 클래스] 공유 10 유용한 PHP 검증 코드 코드

5. NET 코드 튜토리얼을 통해 그래픽 인증 코드를 완성하세요

위 내용은 Java 기반 인증 코드 생성 기능 예제 튜토리얼의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!