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

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)改变验证码类型。

Java生成随机图片验证码工具类相关推荐

  1. 实现Java生成随机图片验证码

    前言 这篇文章主要介绍了如何通过Java如何生成验证码并验证.验证码的作用我想必大家都知道,话不多说开始实施! 提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言 1.项 ...

  2. java 生成随机md5_Java常用工具类(计算MD5,验证码随机生成,天数差值计算)

    写这个博文的目的是为了怕哪天自己的电脑崩溃了,以前写的那些代码就没了,所以将自己写的工具类贴出来,方便以后去使用,也避免自己反复去创造轮子, 也可以对这些方法进行简单修改来完成业务需求,这样就可以极大 ...

  3. java生成随机用户名(工具类)

    随机生成中文用户名 //自动生成名字(中文)public static String getRandomJianHan(int len) {String ret = "";for ...

  4. aliyun短信服务包含随机生成四位数字验证码工具类

    .1.pom文件 <dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sd ...

  5. 分享一个Java生成二维码工具类

    分享一个Java生成二维码工具类 直接上代码: 1.CodeUtil.class package top.lrshuai.blog.util;import java.awt.BasicStroke; ...

  6. Java生成各种随机数的工具类

    介绍 在Java开发中,经常需要生成各种随机数,其中Integer,Long,Float,Decimal用的最多,下面就来封装一个随机数工具类吧 代码 根据业务设置同一类型数值的不同形式,会使用Ran ...

  7. python 基于pillow模块生成随机图片验证码教程

    效果图 我们先来看一下大致的效果图. 以上图形都是用非常基础的元素随机构成的:点,线,曲线,文本.而pillow模块远远不止这些功能,如果学好了它,真的就是你想怎么花就怎么花. 那么现在我们就去学习一 ...

  8. java生成二维码工具类

    1,先引入谷歌的插件zxing的maven坐标 <!-- 二维码 --><dependency><groupId>com.google.zxing</grou ...

  9. java中提供的好用的生成随机数字的工具类(可用来当验证码)

    //验证码位数 是否含有字母 是否含有数字String code=RandomStringUtils.random(4, true, true);System.out.println("验证 ...

最新文章

  1. 一个正在加载网页的进度条,加载完后,自动消失?
  2. 关于提高代码复用性的几个知识点的回顾
  3. 竞赛发布|100万奖金寻DT时代“最强大脑”!
  4. html两个div间有白线,html-在特定浏览器宽度下,白线出现在渐变填充div的末尾
  5. 【原创,提供下载】winfrom 打印表格,字符串的封装
  6. Alpine Linux:从漏洞发现到代码执行
  7. mysql架构 三级主从同步_MySQL 主从同步架构中你不知道的“坑”
  8. 【B/S】ASP.NET---验证码-生成和切换
  9. provide sth for sb; provide sb with sth
  10. Excel对比不同Sheet的关键词个数匹配(VLOOKUP的应用)
  11. 吾爱破解网站访问出错
  12. 【Unity】卡牌游戏教程汇总
  13. java操作.ini文件
  14. 用Xilinx的FPGA实现HDMI(DVI)接收器
  15. 《高仿支付宝运动轨迹七日曲线图》
  16. 城市内涝地埋式积水监测系统解决方案
  17. arm+linux+分辨率无效,Arm NPU的超分辨率!
  18. PaddleRec与Milvus深度结合,手把手带你体验工业级推荐系统召回速度
  19. 电脑桌面计算机的管理在哪,电脑设备管理器在哪里打开?5种打开方法总有适合你...
  20. 面试题:将字符串中的中英文分开显示

热门文章

  1. 硅芯思见:SystemVerilog中unpacked数组的assignment pattern
  2. 论文写作技巧----公式
  3. 让阿里再次伟大--钉钉如何长成独角兽的?
  4. 运用java打印出菱形
  5. 《卓有成效的管理者》笔记,第一章 卓有成效是可以学会的
  6. 道路匹配MapMatching:GPS轨迹点常用聚类算法介绍(K-Means聚类、蚁群算法等)
  7. 关于 Java 的线程状态
  8. RTSP 协议详细介绍
  9. 【RTSP/RTP流媒体】10、编写简单的RTSP客户端
  10. stanford-corenlp 中各词性含义标注