用java写一段生成动态验证码的代码
时间: 2023-09-04 17:12:12 浏览: 104
Java 生成动态验证码
以下是用 Java 生成动态验证码的示例代码:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CaptchaUtil {
private static final int WIDTH = 120;
private static final int HEIGHT = 40;
private static final int CODE_LENGTH = 4;
private static final int LINE_COUNT = 20;
private static final int FONT_SIZE = 20;
public static void generateCaptcha(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
// 生成验证码
String captchaCode = generateCode(CODE_LENGTH);
session.setAttribute("captchaCode", captchaCode);
// 生成图片
BufferedImage captchaImage = generateImage(captchaCode);
// 输出图片到客户端
response.setContentType("image/png");
try (ServletOutputStream out = response.getOutputStream()) {
ImageIO.write(captchaImage, "png", out);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String generateCode(int length) {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(chars.charAt(random.nextInt(chars.length())));
}
return sb.toString();
}
private static BufferedImage generateImage(String captchaCode) {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 填充背景色
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
// 画干扰线
Random random = new Random();
for (int i = 0; i < LINE_COUNT; i++) {
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), random.nextInt(WIDTH), random.nextInt(HEIGHT));
}
// 写验证码
g.setFont(new Font("Arial", Font.PLAIN, FONT_SIZE));
for (int i = 0; i < captchaCode.length(); i++) {
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.drawString("" + captchaCode.charAt(i), 25 * i + 10, HEIGHT / 2 + 5);
}
g.dispose();
return image;
}
}
```
这段代码会生成一个包含随机验证码的 PNG 图片,并输出到客户端。在生成图片的过程中,会生成一些干扰线以及随机颜色的验证码字符。通过 `session` 存储生成的验证码,在客户端提交表单时验证验证码是否正确即可。
阅读全文