java 自定义生成验证码

张小三呀

共 28694字,需浏览 58分钟

 ·

2024-03-22 18:00

说明

项目登录或者其他重要的操作中都要生成验证码,其重要性在此不多说。

主要是介绍自己封装的验证码生成工具类的使用。


建议安装lombok插件,不使用此插件则需要手动生成get、set方法

此工具类不需要引入第三方jar依赖。

验证码说明:

验证码由数字和字母组成

支持自定义验证码位数

支持自定义验证码生成规则

支持自定义验证码图片宽高

支持验证码生成图片保存到指定路径

支持验证码转成base64编码

支持自定义验证码文件和base64编码前缀格式

效果展示

da33b0155d795fc095d297d9c29a0368.webp

Base64编码的文件类型枚举类

      
         
      
      
        import lombok.Getter;
      
      
        
          
@Getter public enum Base64FileTypeEnum { // 文件类型 BASE64_FILETYPE_DOC(".doc", "data:application/msword;base64"), BASE64_FILETYPE_DOCX(".docx", "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64"), BASE64_FILETYPE_XLS(".xls", "data:application/vnd.ms-excel;base64"), BASE64_FILETYPE_XLSX(".xlsx", "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64"), BASE64_FILETYPE_PDF(".pdf", "data:application/pdf;base64"), BASE64_FILETYPE_PPT(".ppt", "data:application/vnd.ms-powerpoint;base64"), BASE64_FILETYPE_PPTX(".pptx", "data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64"), BASE64_FILETYPE_TXT(".txt", "data:text/plain;base64"),
// 图片类型 BASE64_FILETYPE_PNG(".png", "data:image/png;base64"), BASE64_FILETYPE_JPG(".jpg", "data:image/jpeg;base64"), BASE64_FILETYPE_JPEG(".jpeg", "data:image/jpeg;base64"), BASE64_FILETYPE_GIF(".gif", "data:image/gif;base64"), BASE64_FILETYPE_SVG(".svg", "data:image/svg+xml;base64"), BASE64_FILETYPE_ICO(".ico", "data:image/x-icon;base64"), BASE64_FILETYPE_BMP(".bmp", "data:image/bmp;base64");
private String code; private String value;
private Base64FileTypeEnum(String code, String value) { this.code = code; this.value = value; }

}


验证码默认常量值
      
        
          
/** * 说明: 验证码常量 * * @param * @author zhangxiaosan * @create 2022/11/25 * @return */ public interface ValidateCodeConstant { /** * 说明: 默认验证码长度 * * @author zhangxiaosan * @create 2022/11/25 * @param * @return */ Integer size = 4;
/** * 说明: 验证码图片宽 * * @author zhangxiaosan * @create 2022/11/25 * @param * @return */ Integer width = 120;
/** * 说明: 验证码图片高 * * @author zhangxiaosan * @create 2022/11/25 * @param * @return */ Integer height = 40;
/** * 说明: 生成的图片格式,默认jpg * @author zhangxiaosan * @create 2022/11/25 * @param * @return */ String imgType = Base64FileTypeEnum.BASE64_FILETYPE_JPG.getCode().replaceAll("\\.","");
/** * 说明: 生成的base64前缀,默认jpg * @author zhangxiaosan * @create 2022/11/25 * @param * @return */ String base64Prefix = Base64FileTypeEnum.BASE64_FILETYPE_JPG.getValue() + ",";
/** * 说明: 验证码生成图片存储地址,默认不存放图片 * @author zhangxiaosan * @create 2022/11/25 * @param * @return */ String saveImagePath = null; }


验证码生成工具类

      
        
          
import org.springframework.util.StringUtils; import sun.misc.BASE64Encoder; import www.three.commom.constant.ValidateCodeConstant; import www.three.commom.enums.Base64FileTypeEnum;
import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.*; import java.util.*;
/** * 说明: * 生成验证码工具类 * * @author 张小三 * @create 2022-11-24 22:48 * @verson 1.0.0 */ public class ValidateCodeUtil { private static Random random = new Random();
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); }
} }
/** * 生成指定长度的随机数字和字母 * * @param length * @return */ private static String getStringRandom(int length) { String val = ""; Random random = new Random(); for (int i = 0; i < length; i++) { String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; switch (charOrNum) { case "char": int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; val += (char) (random.nextInt(26) + temp); break; case "num": val += String.valueOf(random.nextInt(10)); break; } } return val; }
/** * 创建Base64编码的验证码图片 * * @param w 宽 * @param h 高 * @param code 验证码 * @return * @throws Exception */ private static ByteArrayOutputStream imageToBase64Byte(int w, int h, String code) throws Exception { 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, 250); g2.setColor(c);// 设置背景色 g2.fillRect(0, 2, w, h - 4);
// 绘制干扰线 Random random = new Random(); g2.setColor(getRandColor(160, 200));// 设置线条的颜色 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("Arial", 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.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10); } g2.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, ValidateCodeConstant.imgType, baos); return baos; //return new Base64().encodeToString(baos.toByteArray()); //return new BASE64Encoder().encode(baos.toByteArray()); //return Base64.getEncoder().encodeToString(baos.toByteArray()); }

/** * 创建Base64编码的验证码图片,并保存到指定的路径 * * @param w 宽 * @param h 高 * @param code 验证码 * @param savePath 验证码图片保存的地址 * @return String 单行的base64编码,携带文件前缀 * @throws Exception */ private static String createValidateCodeImageBase(Integer w, Integer h, String code, String savePath) throws Exception { ByteArrayOutputStream baos = imageToBase64Byte(w, h, code); if (StringUtils.hasText(savePath)) { try { File file = new File(savePath); FileOutputStream write = new FileOutputStream(file); byte[] decode = Base64.getEncoder().encode(new BASE64Encoder().encode(baos.toByteArray()).getBytes()); write.write(decode); write.close(); } catch (IOException e) { e.printStackTrace(); } } // 返回不换行的编码 return ValidateCodeConstant.base64Prefix + Base64.getEncoder().encodeToString(baos.toByteArray()); }
/** * 说明: 生成自定义验证码 图片大小 * 验证码宽为 120,高为40,长度为4位,不生成为图片存放 * * @param * @return String 单行的base64编码,携带文件前缀 * @author zhangxiaosan * @create 2022/11/24 */ public static Map<String, Object> createValidateCodeImage(Integer w, Integer h, String code, String savePath) throws Exception { String validateCodeImage = createValidateCodeImageBase(w, h, code, savePath); Map<String, Object> res = new HashMap<String, Object>(); res.put("code", code); res.put("base64", validateCodeImage); res.put("w", w); res.put("h", h); res.put("uuid",UUID.randomUUID()); return res; }

/** * 说明: 生成默认的验证码 * 验证码宽为 120,高为40,长度为4位,不生成为图片存放 * * @param * @return String 单行的base64编码,携带文件前缀 * @author zhangxiaosan * @create 2022/11/24 */ public static Map<String, Object> createValidateCodeImage() throws Exception { String code = getStringRandom(ValidateCodeConstant.size); return createValidateCodeImage( ValidateCodeConstant.width, ValidateCodeConstant.height, code, ValidateCodeConstant.saveImagePath); }
/** * 说明: 生成自定义验证码位数 * 验证码宽为 120,高为40,长度为4位,不生成为图片存放 * * @param * @return String 单行的base64编码,携带文件前缀 * @author zhangxiaosan * @create 2022/11/24 */ public static Map<String, Object> createValidateCodeImage(Integer size) throws Exception { String code = getStringRandom(size); return createValidateCodeImage(ValidateCodeConstant.width, ValidateCodeConstant.height, code, ValidateCodeConstant.saveImagePath); }
/** * 说明: 生成自定义验证码 图片大小 * 长度为4位,不生成为图片存放 * * @param * @return String 单行的base64编码,携带文件前缀 * @author zhangxiaosan * @create 2022/11/24 */ public static Map<String, Object> createValidateCodeImage(Integer w, Integer h) throws Exception { String code = getStringRandom(ValidateCodeConstant.size); return createValidateCodeImage(ValidateCodeConstant.width, ValidateCodeConstant.height, code, ValidateCodeConstant.saveImagePath); }
/** * 说明: 生成自定义验证码 图片大小 * 长度为4位,不生成为图片存放 * * @param * @return String 单行的base64编码,携带文件前缀 * @author zhangxiaosan * @create 2022/11/24 */ public static Map<String, Object> createValidateCodeImage(Integer w, Integer h,Integer size) throws Exception { String code = getStringRandom(size); return createValidateCodeImage( w, h, code, ValidateCodeConstant.saveImagePath); }
}


使用

      
        public static void main(String[] args) throws Exception {
      
      
             ValidateCodeUtil.createValidateCodeImage().forEach((k,v)->{
      
      
                 System.out.println(k+":"+v);
      
      
             });
      
      
         }
      
      
        
          

结果如下:

      
        code: mo1U
      
      
        w: 120
      
      
        base64: data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAoAHgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nz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u5GM9DRRTiTUethyabdXMwlvJlhiByLe3PUf7THrwSCBx3FaNvaW9qCLeCOLPXYoGfr60UVLk3uUopE1FFFIoKKKKACiiigCld6VbXkqzHzIp1BCywuUYZxn2JwoGSOmcdTVeKLUNPkPzfbbY9OAsq/Xs3A69STRRTTJcVuJHq2n3MxhScrLu+aKTKlWz0GeCwPYHnmiiirSM+bVn//2Q==
      
      
        h: 40
      
      
        uuid: 404d2e57-f666-4958-9557-2c113af654bf
      
      
        
          


结果说明:
w : 宽
h :高
code: 验证码
uuid: 验证码唯一标识
base64:验证码图片编码,可以传给前端在html 的 <img src=‘’ "/ > 中展示验证码图片




浏览 32
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报