基于Java实现图形验证码工具类
作者:一线大码
这篇文章主要为大家详细介绍了如何基于Java实现图形验证码工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
工具类:
package com.example.demo.util; import lombok.extern.slf4j.Slf4j; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.security.SecureRandom; /** * 验证码工具类 * * @author wangbo * @since 2024/10/29 */ @Slf4j public class CaptchaGeneratorUtil { private CaptchaGeneratorUtil() { // ... } public static void main(String[] args) throws IOException { // 生成4位随机数字验证码 String text = generateRandomCode(); // 创建验证码图片 BufferedImage image = createImage(text); // 保存图片到文件 ImageIO.write(image, "png", new File("captcha.png")); } private static final SecureRandom RANDOM = new SecureRandom(); /** * 生成4位随机数字字母验证码 */ public static String generateRandomCode() { StringBuilder code = new StringBuilder(); for (int i = 0; i < 4; i++) { int i1 = RANDOM.nextInt(3); if (i1 == 0) { code.append((char) (RANDOM.nextInt(26) + 65)); } else if (i1 == 1) { code.append((char) (RANDOM.nextInt(26) + 97)); } else { code.append(RANDOM.nextInt(10)); } } log.info("生成的验证码文本 text = {}", code); return code.toString(); } /** * 创建验证码图片 */ public static BufferedImage createImage(String text) { log.info("待生成验证码图片的文本 text = {}", text); int width = 75; int height = 25; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 使用Graphics2D以获得更好的图形控制 Graphics2D g2d = image.createGraphics(); try { // 设置背景颜色 g2d.setColor(new Color(0xDCDCDC)); g2d.fillRect(0, 0, width, height); // 设置字体和颜色 g2d.setFont(new Font("Arial", Font.BOLD, 20)); g2d.setColor(new Color(0x004000)); // 确保文本不会超出图像边界 FontMetrics fm = g2d.getFontMetrics(); int textWidth = fm.stringWidth(text); // 居中文本 int x = (width - textWidth) / 2; // 居中文本(基线对齐) int y = (height - fm.getHeight()) / 2 + fm.getAscent(); g2d.drawString(text, x, y); // 添加噪声线 for (int i = 0; i < 5; i++) { g2d.setColor(new Color(RANDOM.nextInt(255), RANDOM.nextInt(255), RANDOM.nextInt(255))); g2d.drawLine(RANDOM.nextInt(width), RANDOM.nextInt(height), RANDOM.nextInt(width), RANDOM.nextInt(height)); } // 设置渲染提示以提高图像质量(可选) g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } finally { // 确保在try块之后释放Graphics2D资源 g2d.dispose(); } return image; } private static final String CAPTCHA_PREFIX = "captcha:"; public static String generateCaptchaRedisKey(String key) { return CAPTCHA_PREFIX + key; } }
生成图片验证码接口(该接口无需权限校验):
/** * 生成图片验证码 * * @param key UUID字符串 */ @GetMapping("/captcha/generator/{key}") public void captchaGenerator(@PathVariable("key") String key, HttpServletResponse response) throws BaseException { userService.captchaGenerator(key, response); }
public void captchaGenerator(String key, HttpServletResponse response) throws BaseException { //查看key的验证码是否已存在 String captchaRedisKey = CaptchaGeneratorUtil.generateCaptchaRedisKey(key); boolean hasKey = Boolean.TRUE.equals(redisTemplate.hasKey(captchaRedisKey)); if (hasKey) { throw new BaseException(ErrorCode.USER_KEY_REPETITION); } String captcha = CaptchaGeneratorUtil.generateRandomCode(); BufferedImage image = CaptchaGeneratorUtil.createImage(captcha); //设置验证码,有效期1分钟 redisTemplate.opsForValue().set(captchaRedisKey, captcha, 60L, TimeUnit.SECONDS); response.setContentType("image/jpeg"); try (ServletOutputStream out = response.getOutputStream()) { ImageIO.write(image, "JPEG", out); } catch (IOException e) { throw new RuntimeException(e); } }
登录接口或者其他涉及验证码的接口进行验证码校验:
//校验验证码 String key = loginPage.getKey(); String captcha = loginPage.getCaptcha(); if (StringUtils.isNullOrEmpty(key) || StringUtils.isNullOrEmpty(captcha)) { throw new BaseException(ErrorCode.USER_KEY_OR_CAPTCHA_NOT_FOUND); } String captchaRedisKey = CaptchaGeneratorUtil.generateCaptchaRedisKey(key); String redisCaptcha = redisTemplate.opsForValue().get(captchaRedisKey); if (StringUtils.isNullOrEmpty(redisCaptcha) || !captcha.equalsIgnoreCase(redisCaptcha)) { throw new BaseException(ErrorCode.USER_CAPTCHA_ERROR); } else { //删除验证码缓存 redisTemplate.delete(captchaRedisKey); }
到此这篇关于基于Java实现图形验证码工具类的文章就介绍到这了,更多相关Java图形验证码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!