java 简单的图片验证码 代码实现
一.创建工具类 BufferImage
package com.xuexi.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
public final class BufferImage {
private static final char[] chars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
private static final int SIZE = 4;
private static final int LINES = 8;
private static final int WIDTH = 100;
private static final int HEIGHT = 32;
private static final int FONT_SIZE = 25;
public static Object[] createImage() {
StringBuffer sb = new StringBuffer();
BufferedImage image = new BufferedImage(
WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics graphic = image.getGraphics();
graphic.setColor(new Color(216, 172, 203, 241));
graphic.fillRect(0, 0, WIDTH, HEIGHT);
Random ran = new Random();
for (int i = 0; i < SIZE; i++) {
int n = ran.nextInt(chars.length);
graphic.setColor(getRandomColor());
graphic.setFont(new Font(
null, Font.BOLD + Font.ITALIC, FONT_SIZE));
graphic.drawString(
chars[n] + "", i * WIDTH / SIZE, HEIGHT / 2 + HEIGHT / 8);
sb.append(chars[n]);
}
for (int i = 0; i < LINES; i++) {
graphic.setColor(getRandomColor());
graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
return new Object[]{sb.toString(), image};
}
public static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256),
ran.nextInt(256), ran.nextInt(256));
return color;
}
public static void main(String[] args) throws IOException {
Object[] objs = createImage();
BufferedImage image = (BufferedImage) objs[1];
OutputStream os = new FileOutputStream("src/main/resources/static/picture/eb1ccd3d99794795bc99553b0b762e73.gif");
ImageIO.write(image, "png", os);
os.close();
}
}
二.创建controller
@RequestMapping(value = "/BufferImage")
protected void createImg(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
Object[] objs = BufferImage.createImage();
String imgcode = (String) objs[0];
HttpSession session = req.getSession();
session.setAttribute("checkcode", imgcode);
BufferedImage img = (BufferedImage) objs[1];
res.setContentType("image/png");
OutputStream os = res.getOutputStream();
ImageIO.write(img, "png", os);
os.close();
}
三.html 页面( 验证码点击刷新)
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" ; content="multipart/form-data; charset=utf-8"/>
<title>Title</title>
</head>
<body>
<h1>hello springboot</h1>
<img id="img" alt="验证码失效" title="点击换一张" src="/BufferImage" onclick="upa()">
</body>
</html>
<script type="text/javascript">
function upa() {
var date = new Date();
$("#img").attr("src", "BufferImage?date=" + date);
}
</script>
<script src="js/jquery-1.11.3.min.js"></script>
四、html页面 (验证码校验)
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" ; content="multipart/form-data; charset=utf-8"/>
<title>Title</title>
</head>
<body>
<h1>hello springboot</h1>
<input name="code" id="code" type="text" onchange="setyzm()">
<img id="img" alt="验证码失效" title="点击换一张" src="/BufferImage" onclick="upa()">
</body>
</html>
<script type="text/javascript">
function setyzm() {
var code = $("#code").val();
$.ajax({
url: "/validcode",
data: {
code: code
},
type: "get",
dataType: "json",
success: function (data) {
if (data.msg != "") {
$("#msg").html(data.msg);
upa()
} else {
$("#msg").html(data.msg);
}
}
});
}
function upa() {
var date = new Date();
$("#img").attr("src", "BufferImage?date=" + date);
}
</script>
<script src="js/jquery-1.11.3.min.js"></script>
- 在后台拿出session 里的验证码和前台输入的验证码做比较
@ResponseBody
@GetMapping("/validcode")
public Object validcode(String code, HttpServletRequest request) {
Map<String, String> result = new HashMap<>();
String msg = "";
String requestCaptcha = (String) request.getSession()
.getAttribute("checkcode");
if (!StringUtils.isEmpty(requestCaptcha)) {
if (!code.equalsIgnoreCase(requestCaptcha)) {
msg = "验证码错误";
}
} else {
msg = "验证码异常,请刷新后重试";
}
result.put("msg", msg);
return result;
}
以上代码都是从csdn里找到的代码,目前已实现,照着来就好