자바 랜 덤 이미지 인증 코드 생 성

4957 단어 자바인증번호
본 논문 의 사례 는 자바 가 랜 덤 이미지 인증 코드 를 생 성 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
효과

프론트 html 코드

<div style="margin-top: 50px;">
  <span>   :</span><input type="text" name="verifyCode" id="verifyCode" style="width: 75px;height: 25px;"/>
  <img id="verifyCodeImg" alt="    " src="/qos/dog/getVerifyCodeImg"
   title="    " onclick="change()">
</div>
주석:여기 src="/qos/dog/getVerify CodeImg"   SpringBoot 페이지 에서 Thymeleaf 의 문법 을 보 여 줍 니 다.
프론트 js 코드

function change() {
  var verifyCode = document.getElementById("verifyCodeImg");
  verifyCode.src = "/qos/dog/getVerifyCodeImg?time=" + Math.random(1000);
 }
 
/*-*/
 
/qos/dog/                
인증 코드,controller 에 util 폴 더 를 새로 만 든 다음 Verify CodeUtil.자바 에 넣 습 니 다.
코드 는 다음 과 같다.

package com.paladin.qos.util;
 
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
 
public class VerifyCodeUtil {
 
 private static final Random random = new Random();
 private static final String[] fontNames = {"  ", "    ", "  ", "Georgia", "    ", "  _GB2312"};
 
 public static String drawImage(ByteArrayOutputStream output) {
  String code = "";
  int width = 50;
  int height = 25;
 
  //       
  BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
 
  Graphics2D g = bi.createGraphics();
 
  //      
  g.setBackground(new Color(255, 255, 255));
  g.clearRect(0, 0, width, height);
 
  StringBuilder stringBuilder = new StringBuilder();
  //         
  for (int i = 0; i < 4; i++) {
   String s = randomChar() + "";  //      ,           ,        ,              
   stringBuilder.append(s);   //   StringBuilder  
   float x = i * 1.0F * width / 4; //     x  
   g.setFont(randomFont());   //    ,  
   g.setColor(randomColor());   //    ,  
   g.drawString(s, x, height - 5);
  }
  code = stringBuilder.toString();//        
 
  //     
  //        (3-5 )int num = random.nextInt(max)%(max-min+1) + min;
  int num = random.nextInt(5) % 3 + 3;
  Graphics2D graphics = (Graphics2D) bi.getGraphics();
  for (int i = 0; i < num; i++) {
   int x1 = random.nextInt(width);
   int y1 = random.nextInt(height);
   int x2 = random.nextInt(width);
   int y2 = random.nextInt(height);
   graphics.setColor(randomColor());
   graphics.drawLine(x1, y1, x2, y2);
  }
  //        
  g.dispose();
  try {
   ImageIO.write(bi, "jpg", output);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return code;//      ,    code,
 
 
 
 }
 
 //    
 private static Font randomFont() {
  int index = random.nextInt(fontNames.length);
  String fontName = fontNames[index];
  int style = random.nextInt(4);   //    4      
  int size = random.nextInt(20) % 6 + 15; //         (10-20    )
  return new Font(fontName, style, size);
 }
 
 //    
 private static Color randomColor() {
  int r = random.nextInt(225);
  int g = random.nextInt(225);
  int b = random.nextInt(225);
  return new Color(r, g, b);
 }
 
 
 //    
 private static char randomChar() {
  //A-Z,a-z,0-9,              
  String str = "0123456789ABCdefghiDEFGHIJopPQRVWXYZabcjklSTUmnqrstKLMNOvuwxyz";
 
  return str.charAt(random.nextInt(str.length()));
 }
 
}
마지막 으로 controller 에서 참조

@RequestMapping("/getVerifyCodeImg")
@ResponseBody

public void getVerifyCodeImg(HttpServletResponse response, HttpSession session) {
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  String code = VerifyCodeUtil.drawImage(output);
  //           session 
  session.setAttribute("verifyCode", code);
  try {
   ServletOutputStream out = response.getOutputStream();
   output.writeTo(out);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
인증 코드 에 관 한 더 많은 글 은 클릭 하여 보 세 요:《자바 인증 코드》
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기