Java生成随机图片验证码工具类

article/2025/9/20 20:17:33

一、第一种生成随机图片验证码

public class VerifyCodeUtil {//生成随机数据的数据源 public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";private static Random random = new Random();/*** 使用系统默认字符源生成验证码* @param verifySize	验证码长度* @return*/public static String generateVerifyCode(int verifySize){return generateVerifyCode(verifySize, VERIFY_CODES);}/*** 使用指定源生成验证码* @param verifySize	验证码长度* @param sources	验证码字符源* @return*/public static String generateVerifyCode(int verifySize, String sources){if(sources == null || sources.length() == 0){sources = VERIFY_CODES;}int codesLen = sources.length();Random rand = new Random(System.currentTimeMillis());StringBuilder verifyCode = new StringBuilder(verifySize);for(int i = 0; i < verifySize; i++){verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));}return verifyCode.toString();}/*** 生成随机验证码文件,并返回验证码值* @param w  宽* @param h  高* @param outputFile    文件* @param verifySize    验证码的长度* @return* @throws IOException*/public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{String verifyCode = generateVerifyCode(verifySize);outputImage(w, h, outputFile, verifyCode);return verifyCode;}/*** 输出随机验证码图片流,并返回验证码值* @param w* @param h* @param os   输出流* @param verifySize* @return* @throws IOException*/public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{String verifyCode = generateVerifyCode(verifySize);outputImage(w, h, os, verifyCode);return verifyCode;}/*** 生成指定验证码图像文件* @param w* @param h* @param outputFile* @param code* @throws IOException*/public static void outputImage(int w, int h, File outputFile, String code) throws IOException{if(outputFile == null){return;}File dir = outputFile.getParentFile();if(!dir.exists()){dir.mkdirs();}try{outputFile.createNewFile();FileOutputStream fos = new FileOutputStream(outputFile);outputImage(w, h, fos, code);fos.close();} catch(IOException e){throw e;}}/*** 输出指定验证码图片流* @param w* @param h* @param os* @param code* @throws IOException*/public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{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("Algerian", 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();ImageIO.write(image, "jpg", os);}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);}}}public static void main(String[] args) throws IOException {File dir = new File("F:/verifies");int w = 200, h = 80;for(int i = 0; i < 5; i++){String verifyCode = generateVerifyCode(4);File file = new File(dir, verifyCode + ".jpg");outputImage(w, h, file, verifyCode);}}}   

使用方法(参考)

@ApiOperation("返回验证码图片")
@RequestMapping(value = "/web/getAuthCode",method = RequestMethod.GET,produces = MediaType.IMAGE_JPEG_VALUE)
@ApiImplicitParam(name = "keyCode",value = "当前时间戳",required = true,paramType ="query",dataType = "String")
public void getAuthCode(HttpServletResponse response,String keyCode){//生成的验证码key值  DECODE_CONSTANT 自定义的常量String key = DECODE_CONSTANT+keyCode;ServletOutputStream outputStream = null;try {outputStream = response.getOutputStream();String code = VerifyCodeUtil.outputVerifyImage(120, 40, outputStream,4);if (!StringUtils.hasText(code)){//为空处理log.error("注册模块:生成验证码错误");}//设置60秒过期   设置到redis中jedis.setex(key,60L,code);} catch (IOException e) {e.printStackTrace();}finally {if (!ObjectUtils.isEmpty(outputStream)){try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}jedis.close();}}

二、第二种生成图片验证码的方法
Happy Captcha是一款易于使用的Java验证码软件包,旨在花最短的时间,最少的代码量,实现Web站点的验证码功能,Happy Captcha完全遵循Apache 2.0开源许可协议,作者ramostear。
验证码效果图
可以通过设置.style(CaptchaStyle.IMG)来设置展示为图片或者设置.style(CaptchaStyle.ANIM)展示为动画。
在这里插入图片描述
在这里插入图片描述
使用步骤
1)maven工程仅需引入相关依赖即可

<dependency><groupId>com.ramostear</groupId><artifactId>Happy-Captcha</artifactId><version>1.0.1</version>
</dependency>

2)使用

@GetMapping("/captcha")
@ApiOperation(value = "登录模块生成验证码接口")
public void happyCaptcha(HttpServletRequest request, HttpServletResponse response){//生成验证码  只需要添加一行代码即可生成验证码图片,request和response是必须提供的参数。HappyCaptcha.require(request,response).type(CaptchaType.NUMBER).build().finish();
}

3)校验

@PostMapping("/verify")
public String verify(String code,HttpServletRequest request){//Verification Captchaboolean flag = HappyCaptcha.verification(request,code,true);if(flag){// 校验通过}
}

4)清理
当验证码被使用后,可以通过HappyCaptcha类种的remove()方法将Session中存放的验证码清理掉,避免出现一次验证码多次使用的情况。

@GetMapping("/remove/captcha")
public void removeCaptcha(HttpServletRequest request){HappyCaptcha.remove(request);   
}

验证码类型

通过.type(CaptchaType.ARITHMETIC)改变验证码类型。
在这里插入图片描述


http://chatgpt.dhexx.cn/article/X0sGT3v5.shtml

相关文章

JS实现图片验证码

JS实现图片验证码 新手第一次发博客&#xff0c;还请多多关照 前言 前几天Net老师布置了一道实验作业&#xff0c;用JS实现文字验证码和简单的图片验证码&#xff0c;要求使用阿里巴巴矢量并且至少能更换三张图片完成 一、实验效果如图 解锁之前解锁成功 示例&#xff1a;…

springboot实现图片验证码登录

之前也看到网上有关于验证码的项目&#xff0c;但是自己试了几个不太行&#xff0c;没有较完整的项目&#xff0c;于是东拼西凑加上自己又稍微添加了一点功能。 现在这个项目可以实现的功能&#xff1a; 基于图片验证码登录&#xff0c;验证码输入正确可以跳转到成功页面&…

apifox图片验证码显示

添加后置脚本 脚本内容如下&#xff1a; var resp {response: pm.response.json() } let imgresp.response.data let template <img src"{{img}}" /> pm.visualizer.set(template,img)在此查看图片验证码

JS实现图片验证码功能

JS实现图片验证码功能 点关注不迷路&#xff0c;欢迎再来&#xff01;以下代码可以直接copy运行&#xff0c;不需要引入jquery.jar 1. html代码 <% page language"java" contentType"text/html; charsetUTF-8" pageEncoding"UTF-8"%> &l…

node实现图片验证码

使用node来做一个图片验证码 做一个下面的小案例&#xff0c;应该能够很快的理解。 首先我们需要创建一个项目。 使用express搭建一个简单的服务器。 安装express。 yarn add express在app文件下这样配置。 const express require(express) const app express() app.use…

Java实现图片验证码

我们在一些网站注册的时候&#xff0c;经常需要填写以上图片的信息。 这种图片验证方式是我们最常见的形式&#xff0c;它可以有效的防范恶意攻击者采用恶意工具,调用“动态验证码短信获取”接口进行动态短信发送, 导致接入用户短信被刷&#xff0c;造成账号余额损失。同时这种…

图片验证码

通过下面这个方法可以得到随机验证码&#xff1a; public String getIdentifyCode(){//得到验证码&#xff08;数字大小写字母&#xff09;String str"";Random randnew Random();for(int i0;i<6;i){switch(rand.nextInt(3)){case 0:int a(int) (Math.random()*26…

图片验证码破解

2.8图片验证码破解 在测试web平台时&#xff0c;难以避免的就是登录&#xff0c;登录的时候就会需要输入验证码&#xff01;有的是图型验证码有的是滑动验证码&#xff0c;那么在自动化中如何破解验证码&#xff1f;这里只介绍简单的图片验证码。 一般来说破解这种图形验证码…

Java实现图片验证码功能

文章目录 一、背景二、实现步骤1、maven中加入依赖2、CaptchaController.java3、生成验证码配置4、CaptchaService.java接口5、CaptchaServiceImpl.java实现类6、增加验证码校验涉及文件 一、背景 在实现登录功能时&#xff0c;为了防止特定的程序暴力破解&#xff0c;一般为了…

python 图片验证码

1.图片验证码第一步 # 导入绘图库 from PIL import ImageDraw, Image, ImageFont 2.生成图片验证类 # 图片验证类 class ImgCode(BaseHandler):# 定义随机颜色实例方法def get_random_color(self):R random.randrange(255)G random.randrange(255)B random.randrange(255)…

java 生成图片验证码

https://vimsky.com/zh-tw/examples/detail/java-class-javax.servlet.ServletOutputStream.html 开发过程中&#xff0c;需要服务端返回验证码图片给前台&#xff0c;想想该如何实现呢&#xff1f; 1、字节流的输入输出 2、生成一个验证码&#xff0c;自定义字母数字混合实现…

C# 图片验证码简单例子

C# 图片验证码简单例子 一、简述 记--使用PictureBox绘制验证码。 例子&#xff1a;外链:https://wwm.lanzouq.com/b0cafckej 密码:cxxn 二、效果 三、工程结构 四、源文件 Form1.cs文件 using System; using System.Drawing; using System.Windows.Forms;namespace Verifi…

springboot图片验证码

前言: 大家好&#xff01;我是小小&#xff01;今天我们用五分钟来用springboot实现我们常用的图形验证码功能模块&#xff01; 用户登录几乎是一个线上系统必不可少且使用相对比较频繁的一个模块&#xff0c;为了防止恶意暴力尝试&#xff0c;防止洪水攻击、防止脚本自动提交…

JavaWeb总结之通过Servlet生成验证码图片

项目地址:https://github.com/zhangzeminzZ/ServletStudy 目录 1.BufferedImage类介绍2.在Form表单中使用验证码图片3.服务器端对form表单提交上来的验证码处理 1.BufferedImage类介绍 生成验证码图片主要用到了一个BufferedImage类 创建一个DrawImage Servlet&#xff0c;用…

网站安全检测之图片验证码

2019独角兽企业重金招聘Python工程师标准>>> 在对网站安全进行整体的安全检测的时候&#xff0c;用户登陆以及用户留言&#xff0c;评论&#xff0c;设置支付密码&#xff0c;以及一些网站功能方面都会用到图片验证码&#xff0c;针对于验证码我们SINE安全对其进行了…

实现图片验证码【详细代码】

实际开发过程中经常遇到要实现图片验证码来防止外部使用脚本刷接口&#xff0c;所以说图片验证码是很有必要的一个小功能。 html <!--- 注册页面整增加图形验证码功能,这里为了更贴近企业级业务&#xff0c;我们在注册页面整增加图形验证码功能--> <div class"u…

图片验证码实现的几种方式

一、Google Kaptcha 1、简介 kaptcha 是一个非常实用的验证码生成工具。有了它&#xff0c;你可以生成各种样式的验证码&#xff0c;因为它是可配置的。kaptcha工作的原理是调用 com.google.code.kaptcha.servlet.KaptchaServlet&#xff0c;生成一个图片。同时将生成的验证码…

ajax请求后台返回数据

功能介绍&#xff1a;最近学习在做一个新闻管理系统&#xff0c;其中有一个模块做的是一个排行榜功能&#xff0c;分为东部联盟和西部联盟&#xff0c;当我点击他的时候&#xff0c;排行的数据会发生变化。由于这一块怎么整个页面中的一小块&#xff0c;所以使用的是局部刷新页…

如何取消ajax请求

之前在面试的时候&#xff0c;被面试官问到了如何取消ajax请求&#xff0c;然鹅并不知道&#xff0c;被刷之后痛定思痛&#xff0c;总结了原生XHR、jquery、axios取消ajax请求的方法。 原生XHR 对于原生XHR对象来说&#xff0c;取消的ajax的关键是调用XHR对象的.abort()方法 …

HTML AJAX请求调用

html ajax请求 ------------------温故而知新,可以装逼矣-------------------- 大佬提出需求&#xff0c;访问html文件&#xff0c;动态响应文章内容 作为一个纯正&#xff08;半吊子&#xff09;的JAVA后端写太多前后端分离的项目&#xff0c;太久没接触前端知识。头都是炸的…