登录页面经常需要生成图片验证码
本文提供一个封装好的验证码生成工具类,可以直接调用生成图片验证码,返回BASE64编码的图片字节字符串。

项目结构:

下面是实战代码:

第一步:

新建工程,引入springboot依赖,创建启动类,创建controller接口
VerifyCodeController.class:

第二步:导入工具类

package com.tzq.test.util;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;public class VerifyCodeUtil {private final static Logger logger = LoggerFactory.getLogger(VerifyCodeUtil.class);// 生成随机数的源private final static String VERIFY_CODE_SRC = "0123456789";/*** 生成验证码** @param width          图片宽度* @param height         图片长度* @param verifyCodeSize 验证码个数* @param outputStream   输出流* @return 验证码*/public static String generateVerifyCode(int width, int height, int verifyCodeSize, OutputStream outputStream) {// 生成 verifyCodeSize 个随机数String verifyCode = VerifyCodeUtil.getRandomVerifyCode(verifyCodeSize, VERIFY_CODE_SRC);logger.debug("【验证码】生成 {} 位验证码:{}", verifyCodeSize, verifyCode);// 创建指定长宽的图片BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D graphics2D = bufferedImage.createGraphics();graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// 设置边框颜色Color randomColor = VerifyCodeUtil.getRandomColor(100, 150);graphics2D.setColor(Color.GRAY);graphics2D.fillRect(0, 0, width, height);// 设置背景颜色randomColor = VerifyCodeUtil.getRandomColor(200, 250);graphics2D.setColor(randomColor);graphics2D.fillRect(0, 2, width, height - 3);// 设置字体graphics2D.setColor(VerifyCodeUtil.getRandomColor(100, 150));graphics2D.setFont(new Font("Consolas", Font.ITALIC, (int) (height * 0.9)));//绘制干扰线VerifyCodeUtil.drawInterferenceLine(graphics2D, width, height);// 添加噪点VerifyCodeUtil.drawNoise(bufferedImage, width, height);// 扭曲图片VerifyCodeUtil.twist(graphics2D, width, height, randomColor);// 写入验证码VerifyCodeUtil.writeVerifyCode(graphics2D, verifyCode, width, height);try {graphics2D.dispose();ImageIO.write(bufferedImage, "jpg", outputStream);outputStream.flush();} catch (IOException e) {e.printStackTrace();logger.error("【验证码】生成异常:{}", e);}return verifyCode;}/*** 写入验证码** @param graphics2D* @param verifyCode* @param width* @param height*/private static void writeVerifyCode(Graphics2D graphics2D, String verifyCode, int width, int height) {Random rand = new Random();char[] chars = verifyCode.toCharArray();for (int i = 0; i < verifyCode.length(); i++) {// 为每个验证码指定不同的颜色graphics2D.setColor(VerifyCodeUtil.getRandomColor(80, 150));// 旋转验证码// FIXME 旋转后的验证码辨识度太低,待完善
//            AffineTransform affineTransform = new AffineTransform();
//            double angle = Math.PI / 8 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1);
//            affineTransform.setToRotation(angle, (new Integer(width).doubleValue() / verifyCode.length()) * i, height * 0.1 / 2);
//            graphics2D.setTransform(affineTransform);// 绘制字符数组graphics2D.drawChars(chars, i, 1, (int) (width / (double) (verifyCode.length() + 2) * (i + 1)), (int) (height * 0.75));}}/*** 绘制噪点** @param image* @param width* @param height*/private static void drawNoise(BufferedImage image, int width, int height) {// 噪声率float yawpRate = 0.1f;int area = (int) (yawpRate * width * height);for (int i = 0; i < area; i++) {int x = (int) (Math.random() * width);int y = (int) (Math.random() * height);int rgb = VerifyCodeUtil.getRandomIntColor();image.setRGB(x, y, rgb);}}/*** 绘制干扰线** @param graphics2D* @param width* @param height*/private static void drawInterferenceLine(Graphics2D graphics2D, int width, int height) {// 设置线条的颜色graphics2D.setColor(VerifyCodeUtil.getRandomColor(160, 200));// 20条干扰线for (int i = 0; i < 20; i++) {int x1 = (int) (Math.random() * width * 0.7);int y1 = (int) (Math.random() * height * 0.7);graphics2D.drawLine(x1, y1, (int) (x1 + x1 * 0.3), (int) (y1 + y1 * 0.3));}}/*** 扭曲图片** @param graphics* @param width* @param height* @param color*/private static void twist(Graphics graphics, int width, int height, Color color) {int period = (int) ((Math.random() * height * 0.3) + height * 0.2);for (int i = 0; i < width; i++) {double sin = (double) (period >> 1) * Math.sin(i / (double) period + Math.PI);graphics.copyArea(i, 0, 1, height, 0, (int) sin);graphics.setColor(color);graphics.drawLine(i, (int) sin, i, 0);graphics.drawLine(i, (int) sin + height, i, height);}}/*** 产生随机颜色,但指定范围** @param fc* @param bc* @return*/private static Color getRandomColor(int fc, int bc) {if (fc > 255) {fc = 255;} else if (bc > 255) {bc = 255;}int r = fc + (int) (Math.random() * (bc - fc));int g = fc + (int) (Math.random() * (bc - fc));int b = fc + (int) (Math.random() * (bc - fc));return new Color(r, g, b);}/*** 获取 int 类型颜色** @return*/private static int getRandomIntColor() {int[] rgb = new int[3];for (int i = 0; i < 3; i++) {rgb[i] = (int) (Math.random() * 255);}int color = 0;for (int c : rgb) {color = color << 8;color = color | c;}return color;}/*** 生成随机数字符串,指定大小和源** @param verifyCodeSize* @param verifyCodeSrc* @return*/private static String getRandomVerifyCode(int verifyCodeSize, String verifyCodeSrc) {StringBuffer stringBuffer = new StringBuffer(verifyCodeSize);for (int i = 0; i < verifyCodeSize; i++) {stringBuffer.append(verifyCodeSrc.charAt((int) (Math.random() * verifyCodeSrc.length())));}return stringBuffer.toString();}/*** 生成验证码** @param verifyCodeSize 验证码个数* @return 验证码*/public static String generateVerifyCode(int verifyCodeSize) {// 生成 verifyCodeSize 个随机数String verifyCode = VerifyCodeUtil.getRandomVerifyCode(verifyCodeSize, VERIFY_CODE_SRC);logger.debug("【验证码】生成 {} 位验证码:{}", verifyCodeSize, verifyCode);return verifyCode;}}

第三步测试

启动服务,打开浏览器:
http://localhost:8058/getVerifyCode?width=100&height=50&verfyCodeSize=4

返回值为BASE64编码的图片字节字符串,前端使用时需要加前缀:data:image/jpeg;base64。
打开一个base64编码转换为图片的网址:http://tool.chinaz.com/tools/imgtobase

看到生成验证码成功。

项目源码地址:https://gitee.com/tang-zhiqian0808/learning-code/tree/master/testVerifyCode

spring封装VerifyCodeUtil工具类,生成图片验证码相关推荐

  1. Spring 的优秀工具类盘点---转

    第 1 部分: 文件资源操作和 Web 相关工具类 http://www.ibm.com/developerworks/cn/java/j-lo-spring-utils1/ 文件资源操作 文件资源的 ...

  2. SpringBoot中操作spring redis的工具类

    场景 SpringBoot+Vue+Redis实现前后端分离的字典缓存机制: https://blog.csdn.net/badao_liumang_qizhi/article/details/108 ...

  3. Spring 的优秀工具类盘点

    Spring 的优秀工具类盘点---转 第 1 部分: 文件资源操作和 Web 相关工具类 http://www.ibm.com/developerworks/cn/java/j-lo-spring- ...

  4. SpringBoot整合Redis+mybatis,封装RedisUtils工具类等实战(附源码)

    点击上方蓝色字体,选择"标星公众号" 优质文章,第一时间送达 关注公众号后台回复pay或mall获取实战项目资料+视频 作者:陈彦斌 cnblogs.com/chenyanbin/ ...

  5. Java封装OkHttp3工具类

    点击关注公众号,Java干货及时送达  作者:如漩涡 https://blog.csdn.net/m0_37701381 Java封装OkHttp3工具类,适用于Java后端开发者 说实在话,用过挺多 ...

  6. writeValueAsString封装成工具类

    封装成工具类 [java] view plaincopyprint? <span style="font-family:Microsoft YaHei;">public ...

  7. MySQL数据库学习笔记(十一)----DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)...

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  8. 基于AFNetworking的封装的工具类

    基于AFNetworking的封装的工具类MXERequestService // // MXERequestService.h // testAFNetWorking // // Created b ...

  9. 分页封装实用工具类及其使用方法

    分页封装实用工具类及其使用方法 作者: javaboy2012 Email:yanek@163.com qq:    1046011462 package com.yanek.util; import ...

  10. Springboot+axios+vue使用VerifyCodeUtils工具类实现验证码图片功能

    一.环境准备 idea java 1.8 maven 3.6.3 操作系统:window10 vue.min.js axios.min.js 二.VerifyCodeUtils工具类 import j ...

最新文章

  1. 廖雪峰的数据分析课!
  2. 从别人那拷下来的几点Session使用的经验(转载)
  3. MATLAB从入门到精通-如何在MATLAB中实现各种特殊上标?
  4. why-use-getters-and-setters
  5. HttpURLConnection根据URL下载图片
  6. TensorFlow学习笔记(十九) 基本算术运算和Reduction归约计算
  7. php判断秒为两位数,判“新”函数:得到今天与明天的秒数
  8. M1 macbook值得购买吗?关于M1芯片macbook的三点购买建议
  9. JMeter记录篇2——性能测试基础(2)
  10. 服装这个行业其实一直有点尴尬
  11. C++之unique_ptr
  12. 学习HashMap的笔记
  13. 也论不使用第三个变量交换两个变量的值[C#]
  14. manjaro开启热点设置密码WPA/WPA2后iphone连不上
  15. 未来交通技术发展现状和我国面临的挑战
  16. TPshop商城环境搭建(一)
  17. 如何进行隐私协议测试
  18. echart 边框线_echarts 饼图给外层加边框
  19. CSS font-style斜体字体倾斜体样式
  20. OpenCL学习笔记一

热门文章

  1. eda多功能数字钟课程设计_EDA电子钟多功能数字时钟课程设计(含代码)[优秀]...
  2. 产品能力提升|《点石成金·访客至上的Web和移动可用性设计秘籍》
  3. 局域网ip冲突检测工具_python 小工具实现 windows笔记本与 ipad数据互传
  4. 国内十大HR系统品牌
  5. css宋体代码_CSS字体代码
  6. access连接mysql_如何正确连接access数据库
  7. php 加密视频播放地址,如何在PHP中实现Clear-Key视频加密并以HTML格式播放
  8. H5调用摄像头扫码详解
  9. 三款好用的前端代码编辑器推荐
  10. 【魔改蜗牛星际】A单主板变“皇帝板”扩展到8个SATA口