可以提供一段生成图片验证码的代码吗
时间: 2024-02-28 16:52:06 浏览: 75
生成验证码图片的代码
以下是基于Java Servlet API 3.0的生成图片验证码的示例代码:
```java
@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 120;
private static final int HEIGHT = 40;
private static final int LENGTH = 6;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
String captcha = generateCaptcha();
request.getSession().setAttribute("captcha", captcha);
Font font = new Font("Arial", Font.BOLD, 20);
g.setFont(font);
g.setColor(Color.BLACK);
g.drawString(captcha, 10, 25);
g.dispose();
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
ImageIO.write(image, "jpeg", out);
out.close();
}
private String generateCaptcha() {
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < LENGTH; i++) {
sb.append((char) (random.nextInt(26) + 'a'));
}
return sb.toString();
}
}
```
在上面的示例中,我们使用 Java 的 BufferedImage 类创建了一个图片对象,然后使用 Graphics2D 类绘制验证码。我们使用了随机数生成器来生成验证码,然后将其存储在 Session 中,以便在提交表单时验证验证码。最后,将图片输出到响应中。
阅读全文