1.新建一个springboot的项目

2.导入坐标

<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>

3.编写配置

1)颜色配置类

package com.zys.springboottestexample.common.kaptcha;

import org.assertj.core.util.Lists;

import java.awt.*;
import java.util.List;
import java.util.Random; /**
* 验证码颜色
*/
public class KaptchaColor { public static Color getColor() { List<Color> colors = Lists.newArrayList();
colors.add(new Color(0, 135, 255));
colors.add(new Color(51, 153, 51));
colors.add(new Color(255, 102, 102));
colors.add(new Color(255, 153, 0));
colors.add(new Color(153, 102, 0));
colors.add(new Color(153, 102, 153));
colors.add(new Color(51, 153, 153));
colors.add(new Color(102, 102, 255));
colors.add(new Color(0, 102, 204));
colors.add(new Color(204, 51, 51));
colors.add(new Color(128, 153, 65));
Random random = new Random();
int colorIndex = random.nextInt(10);
return colors.get(colorIndex);
}
}

2)降噪配置

package com.zys.springboottestexample.common.kaptcha;

import com.google.code.kaptcha.NoiseProducer;
import com.google.code.kaptcha.util.Configurable; import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random; /**
* 验证码加噪处理
*/
public class KaptchaNoise extends Configurable implements NoiseProducer {
public KaptchaNoise() {
} @Override
public void makeNoise(BufferedImage image, float factorOne, float factorTwo, float factorThree, float factorFour) { int width = image.getWidth();
int height = image.getHeight();
Graphics2D graph = (Graphics2D)image.getGraphics();
graph.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
graph.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
Random random = new Random();
int noiseLineNum = random.nextInt(3);
if(noiseLineNum == 0){
noiseLineNum = 1;
}
for (int i = 0; i < noiseLineNum; i++){
graph.setColor(KaptchaColor.getColor());
graph.drawLine(random.nextInt(width), random.nextInt(height), 10 + random.nextInt(20), 10 + random.nextInt(20));
} graph.dispose();
}
}

3)字体配置

package com.zys.springboottestexample.common.kaptcha;

import com.google.code.kaptcha.util.Configurable;

import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.util.Random; /**
* 验证码字体生成(根据文字内容)
*/
public class KaptchaWordRenderer extends Configurable implements com.google.code.kaptcha.text.WordRenderer { public KaptchaWordRenderer() {
} @Override
public BufferedImage renderWord(String word, int width, int height) {
int fontSize = this.getConfig().getTextProducerFontSize();
Font[] fonts = this.getConfig().getTextProducerFonts(fontSize);
int charSpace = this.getConfig().getTextProducerCharSpace();
BufferedImage image = new BufferedImage(width, height, 2); Graphics2D g2D = image.createGraphics();
g2D.setColor(Color.WHITE);
RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2D.setRenderingHints(hints);
g2D.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); FontRenderContext frc = g2D.getFontRenderContext();
Random random = new Random();
int startPosY = (height - fontSize) / 5 + fontSize;
char[] wordChars = word.toCharArray();
Font[] chosenFonts = new Font[wordChars.length];
int[] charWidths = new int[wordChars.length];
int widthNeeded = 0; int startPosX;
for(startPosX = 0; startPosX < wordChars.length; ++startPosX) {
chosenFonts[startPosX] = fonts[random.nextInt(fonts.length)];
char[] charToDraw = new char[]{wordChars[startPosX]};
GlyphVector gv = chosenFonts[startPosX].createGlyphVector(frc, charToDraw);
charWidths[startPosX] = (int)gv.getVisualBounds().getWidth();
if (startPosX > 0) {
widthNeeded += 2;
} widthNeeded += charWidths[startPosX];
} startPosX = (width - widthNeeded) / 2; for(int i = 0; i < wordChars.length; ++i) {
g2D.setColor(KaptchaColor.getColor());
g2D.setFont(chosenFonts[i].deriveFont(Font.PLAIN));
char[] charToDraw = new char[]{wordChars[i]};
g2D.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY);
startPosX = startPosX + charWidths[i] + charSpace;
} return image;
} }

4)验证码主要配置

package com.zys.springboottestexample.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.zys.springboottestexample.common.kaptcha.KaptchaNoise;
import com.zys.springboottestexample.common.kaptcha.KaptchaWordRenderer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.util.Properties; /**
* 谷歌图片验证码配置
*/
@Configuration
public class KaptchaConfig { @Bean
public DefaultKaptcha getDefaultKaptcha() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
//图片是否有边框
properties.setProperty("kaptcha.border", "no");
//图片的边框颜色
properties.setProperty("kaptcha.border.color", "34,114,200");
//图片的大小
properties.setProperty("kaptcha.image.width", "125");
properties.setProperty("kaptcha.image.height", "45");
//文字内容
properties.setProperty("kaptcha.textproducer.char.length", "5");
//图片背景颜色
properties.setProperty("kaptcha.background.clear.from", "white");
properties.setProperty("kaptcha.background.clear.to", "white"); properties.setProperty("kaptcha.word.impl", KaptchaWordRenderer.class.getName());
properties.setProperty("kaptcha.noise.impl", KaptchaNoise.class.getName()); Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
} }

4.编写接口

@RestController
@RequestMapping("/kaptcha")
public class KaptchaController { @Autowired
private DefaultKaptcha defaultKaptcha; @GetMapping("/img")
public void createImg(HttpServletResponse response) throws IOException {
//生成验证码文字
String kaptchaText = defaultKaptcha.createText();
System.out.println(kaptchaText);
//根据文字生成图片
BufferedImage image = defaultKaptcha.createImage(kaptchaText);
ImageIO.write(image, "jpg", response.getOutputStream());
} }

5.测试

启动项目,访问http://localhost:8080/kaptcha/img就可以看到图片。

说明:对于图片,也可以使用流的方式返回给前端,然后前端直接使用img标签,把数据给src属性即可。修改后的代码如下

     //生成验证码文字
String kaptchaText = defaultKaptcha.createText();
System.out.println(kaptchaText);
//根据文字生成图片
BufferedImage image = defaultKaptcha.createImage(kaptchaText);
ByteArrayOutputStream outputStream =new ByteArrayOutputStream();
ImageIO.write(image, "jpg", outputStream);
String base64Code = Base64.encodeBase64String(outputStream.toByteArray());
return base64Code;

SpringBoot使用谷歌方式生成图片验证码的更多相关文章

  1. python 全栈开发,Day85(Git补充,随机生成图片验证码)

    昨日内容回顾 第一部分:django相关 1.django请求生命周期 1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端 请求头和请求体中会包含浏览器的动作(action),这 ...

  2. Django登录(含随机生成图片验证码)注册实例

    登录,生成随机图片验证码 一.登录 - 随机生成图片验证码 1.随机生成验证码 Python随机生成图片验证码,需要使用PIL模块,安装方式如下: pip3 install pillow 1)创建图片 ...

  3. PHP生成图片验证码demo【OOP面向对象版本】

    下面是我今天下午用PHP写的一个生成图片验证码demo,仅供参考. 这个demo总共分为4个文件,具体代码如下: 1.code.html中的代码: <!doctype html> < ...

  4. net生成图片验证码--转自Lisliefor

    目前,机器识别验证码已经相当强大了,比较常见的避免被机器识别的方法,就是将验证码的字符串连到一起,这样就加大的识别的难度,毕竟机器没有人工智能.我找了很多的.net生成图片验证码的例子,后来经过一些修 ...

  5. python PIL图像处理-生成图片验证码

    生成效果如图: 代码 from PIL import Image,ImageDraw,ImageFont,ImageFilter import random # 打开一个jpg图像文件: im = I ...

  6. 前端基于vue,后台采用springboot+shiro的方式搭建的一个移动端商品展示平台

    基于vue实现的移动端商品展示页,可以web-view的方式嵌入到小程序中,布局简约.大气,减少初学者或开发者不必要的工作量.后台维护采用的springboot+shiro的方式,为广大爱好者提供展示 ...

  7. 在.net core web项目中生成图片验证码

    第1步:添加SkiaSharp包引用 Install-Package SkiaSharp 第2步:编写生成图片验证码的代码 using SkiaSharp; //在类文件头部添加引用 public I ...

  8. 利用modelarts和物体检测方式识别验证码

    近来有朋友让老山帮忙识别验证码.在github上查看了下,目前开源社区中主要流行以下几种验证码识别方式: tesseract-ocr模块: 这是HP实验室开发由Google 维护的开源 OCR引擎,内 ...

  9. 【转载】Asp.Net生成图片验证码工具类

    在Asp.Net应用程序中,很多时候登陆页面以及其他安全重要操作的页面需要输入验证码,本文提供一个生成验证码图片的工具类,该工具类通过随机数生成验证码文本后,再通过C#中的图片处理类位图类,字体类,一 ...

随机推荐

  1. 2019 Multi-University Training Contest 4.Divide the Stones(贪心)

    题意:给你n和k (k|n) 有n个数 第i个数权值为i 要你求权值相同且分成k组 且每组的个数为n/k 思路:恶心构造题,首先对于总权值不能分为k份的 显然不能分成 然后 我们把n/k 分奇偶 我们 ...

  2. 2020 ICPC Universidad Nacional de Colombia Programming Contest

    2020 ICPC Universidad Nacional de Colombia Programming Contest A. Approach 三分 显然答案可以三分,注意\(eps\)还有两条 ...

  3. 【poj 1284】Primitive Roots(数论--欧拉函数 求原根个数){费马小定理、欧拉定理}

    题意:求奇质数 P 的原根个数.若 x 是 P 的原根,那么 x^k (k=1~p-1) 模 P 为1~p-1,且互不相同. (3≤ P<65536) 解法:有费马小定理:若 p 是质数,x^( ...

  4. Codeforces Round #343 (Div. 2) E. Famil Door and Roads (树形dp,lca)

    Famil Door's City map looks like a tree (undirected connected acyclic graph) so other people call it ...

  5. Baby-step giant-step算法

    写在前面: 学习笔记,方便复习,学习资料来自网络,注明出处 我们都在努力奔跑,我们都是追梦人 结论 In group theory, a branch of mathematics, the baby ...

  6. Codeforces ECR 83 C. Adding Powers (位运算)

    题意:给你n个数和一个底数k,每个数每次能减去k^i(i=0,1,2,....),每个k^i只能用一次,问是否能够将每个数变为0. 题解:我们将每个数转化为k进制,因为每个k^i只能用一次,所以我们统 ...

  7. Codeforces Round #667 (Div. 3) D. Decrease the Sum of Digits (贪心)

    题意:给你一个正整数\(n\),每次可以对\(n\)加一,问最少操作多少次是的\(n\)的所有位数之和不大于\(s\). 题解:\(n\)的某个位置上的数进位,意味这后面的位置都可以被更新为\(0\) ...

  8. Shell 函数 & 数组

    Shell 函数 函数介绍 # 什么是函数? 具备某一功能的工具 => 函数 事先准备工具的过程 => 函数的定义 遇到应用场景拿来就用 => 函数的调用 # 为何要用函数? 没有引 ...

  9. String的20个方法

    String的20个方法 面试题 1.new和不new的区别 String A="OK"; String B="OK";//会去常量池查找有没有"Ok ...

  10. linux内核编程入门--系统调用监控文件访问

    参考的资料: hello world   https://www.cnblogs.com/bitor/p/9608725.html linux内核监控模块--系统调用的截获  https://www. ...