1. 程式人生 > 程式設計 >java數字和中文算數驗證碼的實現

java數字和中文算數驗證碼的實現

本文介紹了java數字和中文算數驗證碼的實現,分享給大家,具體如下:

效果圖

java數字和中文算數驗證碼的實現java數字和中文算數驗證碼的實現

本文程式碼 https://gitee.com/tothis/java-record/tree/master/src/main/java/com/example/captcha

中文實現參考 https://gitee.com/whvse/EasyCaptcha.git

數字實現參考 https://www.jb51.net/article/190561.htm

程式碼如下

中文演算法

package com.example.captcha;

import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author 李磊
 * @datetime 2020/7/9 20:10
 * @description
 */
@Slf4j
public class ChineseCaptcha {
 // 寬度
 private static final int IMAGE_WIDTH = 160;
 // 高度
 private static final int IMAGE_HEIGHT = 40;
 // 字型大小
 private static final int FONT_SIZE = 28;
 // 干擾線數量
 private static final int IMAGE_DISTURB_LINE_NUMBER = 15;
 // 字尾
 private static final String SUFFIX = "等於?";

 // 漢字數字
 private static final String SOURCE = "零一二三四五六七八九十乘除加減";

 // 計算型別
 private static final Map<String,Integer> calcType = new HashMap<>();
 private static final Random RANDOM = new Random();

 static {
  // 對應SOURCE下標
  calcType.put("*",11);
  calcType.put("/",12);
  calcType.put("+",13);
  calcType.put("-",14);
 }

 // 計算公式
 private String content;
 // 計算結果
 private int result;

 /**
  * 生成影象驗證碼
  */
 public BufferedImage create() {
  createMathChar();
  BufferedImage image = new BufferedImage(IMAGE_WIDTH,IMAGE_HEIGHT,BufferedImage.TYPE_INT_RGB);
  Graphics g = image.getGraphics();
  // 字型顏色
  g.setColor(Color.WHITE);
  // 背景顏色
  g.fillRect(0,IMAGE_WIDTH,IMAGE_HEIGHT);
  g.setColor(color());
  // 圖片邊框
  g.drawRect(0,IMAGE_WIDTH - 1,IMAGE_HEIGHT - 1);
  g.setColor(color());
  for (int i = 0; i < IMAGE_DISTURB_LINE_NUMBER; i++) {
   // 繪製干擾線
   int x1 = RANDOM.nextInt(IMAGE_WIDTH);
   int y1 = RANDOM.nextInt(IMAGE_HEIGHT);
   int x2 = RANDOM.nextInt(13);
   int y2 = RANDOM.nextInt(15);
   g.drawLine(x1,y1,x1 + x2,y1 + y2);
  }
  StringBuilder builder = new StringBuilder();
  for (int i = 0,j = content.length(); i < j; i++) {
   int index;
   if (i == 1) {
    index = calcType.get(String.valueOf(content.charAt(i)));
   } else {
    index = Integer.parseInt(String.valueOf(content.charAt(i)));
   }
   String ch = String.valueOf(SOURCE.charAt(index));
   builder.append(ch);
   drawString((Graphics2D) g,ch,i);
  }
  drawString((Graphics2D) g,SUFFIX,3);
  content = builder.append(SUFFIX).toString();
  g.dispose();
  return image;
 }

 private void createMathChar() {
  StringBuilder number = new StringBuilder();
  // 10以內數字
  int xx = RANDOM.nextInt(10);
  int yy = RANDOM.nextInt(10);
  // 0~3 對應加減乘除
  int round = (int) Math.round(Math.random() * 3);
  if (round == 0) {
   this.result = yy + xx;
   number.append(yy);
   number.append("+");
   number.append(xx);
  } else if (round == 1) {
   this.result = yy - xx;
   number.append(yy);
   number.append("-");
   number.append(xx);
  } else if (round == 2) {
   this.result = yy * xx;
   number.append(yy);
   number.append("*");
   number.append(xx);
  } else {
   // 0不可為被除數 yy對xx取餘無餘數
   if (!(xx == 0) && yy % xx == 0) {
    this.result = yy / xx;
    number.append(yy);
    number.append("/");
    number.append(xx);
   } else {
    this.result = yy + xx;
    number.append(yy);
    number.append("+");
    number.append(xx);
   }
  }
  this.content = number.toString();
  log.info("數字計算公式 {}",this.content);
 }

 private void drawString(Graphics2D g2d,String s,int i) {
  g2d.setFont(new Font("黑體",Font.BOLD,FONT_SIZE));
  int r = RANDOM.nextInt(255);
  int g = RANDOM.nextInt(255);
  int b = RANDOM.nextInt(255);
  g2d.setColor(new Color(r,g,b));
  int x = RANDOM.nextInt(3);
  int y = RANDOM.nextInt(2);
  g2d.translate(x,y);
  int angle = new Random().nextInt() % 15;
  g2d.rotate(angle * Math.PI / 180,5 + i * 25,20);
  g2d.drawString(s,30);
  g2d.rotate(-angle * Math.PI / 180,20);
 }

 // 獲取隨機顏色
 private Color color() {
  int r = RANDOM.nextInt(256);
  int g = RANDOM.nextInt(256);
  int b = RANDOM.nextInt(256);
  return new Color(r,b);
 }

 public String content() {
  return content;
 }

 public int result() {
  return result;
 }
}

數字演算法

此程式碼使用了ttf字型 字型在此處 https://gitee.com/tothis/java-record/tree/master/src/main/resources/font

package com.example.captcha;

import lombok.SneakyThrows;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @author 李磊
 * @datetime 2020/7/9 20:16
 * @description
 */
public class NumberCaptcha {
 // 寬度
 private static final int IMAGE_WIDTH = 160;
 // 高度
 private static final int IMAGE_HEIGHT = 40;
 // 字型大小
 private static final int FONT_SIZE = 28;
 // 字型目錄
 private static final String FONT_PATH = "/font/";
 // 字型列表
 private static final String[] FONT_NAMES = {
   "actionj.ttf","epilog.ttf","headache.ttf","lexo.ttf","prefix.ttf","robot.ttf"
 };

 private static final Random RANDOM = new Random();
 // 計算公式
 private String content;
 // 計算結果
 private int result;

 /**
  * 生成隨機驗證碼
  */
 private void createMathChar() {
  StringBuilder number = new StringBuilder();
  int xx = RANDOM.nextInt(10);
  int yy = RANDOM.nextInt(10);
  // 0~3 對應加減乘除
  int round = (int) Math.round(Math.random() * 3);
  if (round == 0) {
   this.result = yy + xx;
   number.append(yy);
   number.append("+");
   number.append(xx);
  } else if (round == 1) {
   this.result = yy - xx;
   number.append(yy);
   number.append("-");
   number.append(xx);
  } else if (round == 2) {
   this.result = yy * xx;
   number.append(yy);
   number.append("x");
   number.append(xx);
  } else {
   // 0不可為被除數 yy對xx取餘無餘數
   if (!(xx == 0) && yy % xx == 0) {
    this.result = yy / xx;
    number.append(yy);
    number.append("/");
    number.append(xx);
   } else {
    this.result = yy + xx;
    number.append(yy);
    number.append("+");
    number.append(xx);
   }
  }

  content = number.append("=?").toString();
 }

 // 獲取隨機顏色
 private Color color() {
  int r = RANDOM.nextInt(256);
  int g = RANDOM.nextInt(256);
  int b = RANDOM.nextInt(256);
  return new Color(r,b);
 }

 /**
  * 隨機畫干擾圓
  *
  * @param num 數量
  * @param g Graphics2D
  */
 private void drawOval(int num,Graphics2D g) {
  for (int i = 0; i < num; i++) {
   g.setColor(color());
   int j = 5 + RANDOM.nextInt(10);
   g.drawOval(RANDOM.nextInt(IMAGE_WIDTH - 25),RANDOM.nextInt(IMAGE_HEIGHT - 15),j,j);
  }
 }

 @SneakyThrows
 private Font font() {
  int index = RANDOM.nextInt(FONT_NAMES.length);
  Font font = Font.createFont(Font.TRUETYPE_FONT,getClass().getResourceAsStream(FONT_PATH + FONT_NAMES[index]))
    .deriveFont(Font.BOLD,FONT_SIZE);
  return font;
 }

 /**
  * 生成驗證碼圖形
  */
 public BufferedImage create() {
  createMathChar();
  char[] chars = content.toCharArray();
  BufferedImage image = new BufferedImage(IMAGE_WIDTH,BufferedImage.TYPE_INT_RGB);
  Graphics2D g2d = (Graphics2D) image.getGraphics();
  // 填充背景
  g2d.setColor(Color.WHITE);
  g2d.fillRect(0,IMAGE_HEIGHT);
  // 抗鋸齒
  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
  // 畫干擾圓
  drawOval(2,g2d);
  // 畫字串
  g2d.setFont(font());
  FontMetrics fontMetrics = g2d.getFontMetrics();
  // 每一個字元所佔的寬度
  int fx = IMAGE_WIDTH / chars.length;
  // 字元左填充
  int flp = 10;
  for (int i = 0; i < chars.length; i++) {
   String item = String.valueOf(chars[i]);
   g2d.setColor(color());
   // 文字的縱座標
   int fy = IMAGE_HEIGHT - ((IMAGE_HEIGHT - (int) fontMetrics
     .getStringBounds(item,g2d).getHeight()) >> 1);
   g2d.drawString(item,flp + i * fx + 3,fy - 3);
  }
  g2d.dispose();
  return image;
 }

 public String content() {
  return content;
 }

 public int result() {
  return result;
 }
}

測試類

package com.example.captcha;

import com.greenpineyu.fel.FelEngine;
import com.greenpineyu.fel.FelEngineImpl;
import lombok.SneakyThrows;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * @author 李磊
 * @datetime 2020/7/9 20:10
 * @description
 */
public class Main {
 @SneakyThrows
 public static void main(String[] args) {
  // 圖片型別
  String IMAGE_TYPE = "png";
  ChineseCaptcha chinese = new ChineseCaptcha();
  NumberCaptcha number = new NumberCaptcha();

  for (int i = 0; i < 10; i++) {
   BufferedImage image1 = chinese.create();
   // 輸出檔案
   ImageIO.write(image1,IMAGE_TYPE,new File("D:/data/a" + i + ".png"));
   System.out.println(chinese.content() + ' ' + chinese.result());

   BufferedImage image2 = number.create();
   // 輸出檔案
   ImageIO.write(image2,new File("D:/data/b" + i + ".png"));
   System.out.println(number.content() + ' ' + number.result());
  }
 }
}

如需要多級運算如1+2-3*4/5 則需要使用表示式引擎計算 如下為使用fel計算表示式

// fel計算表示式
FelEngine fel = new FelEngineImpl();
System.out.println(3 * 2 + 1);
System.out.println(fel.eval("3*2+1"));
System.out.println(3 * (2 + 1));
System.out.println(fel.eval("3*(2+1)"));

到此這篇關於java數字和中文算數驗證碼的實現的文章就介紹到這了,更多相關java數字和中文算數驗證碼內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!