工具类:
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图形验证码内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论