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 */@Slf4jpublic 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, 0, IMAGE_WIDTH, IMAGE_HEIGHT); g.setColor(color()); // 圖片邊框 g.drawRect(0, 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, 5 + i * 25, 30); g2d.rotate(-angle * Math.PI / 180, 5 + i * 25, 20); } // 獲取隨機顏色 private Color color() { int r = RANDOM.nextInt(256); int g = RANDOM.nextInt(256); int b = RANDOM.nextInt(256); return new Color(r, g, 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, g, 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, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = (Graphics2D) image.getGraphics(); // 填充背景 g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, IMAGE_WIDTH, 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, IMAGE_TYPE, 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數字和中文算數驗證碼內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: