在Javaweb项目中生成图形验证码

时间:2025-04-04 15:21:25
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • public class CaptchaGenerator {
  • private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  • private static final int WIDTH = 150;
  • private static final int HEIGHT = 50;
  • public String generateCaptchaString(int length) {
  • Random r = new Random();
  • StringBuilder captchaStringBuilder = new StringBuilder();
  • for (int i = 0; i < length; i++) {
  • (((())));
  • }
  • return ();
  • }
  • public BufferedImage generateCaptchaImage(String captchaString) {
  • BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
  • Graphics g = ();
  • // 设置背景颜色
  • ();
  • (0, 0, WIDTH, HEIGHT);
  • // 设置字体颜色和字体样式
  • (new Font("Arial", , 40));
  • ();
  • (captchaString, 20, 40);
  • // 添加一些干扰线
  • Random r = new Random();
  • for (int i = 0; i < 10; i++) {
  • int x1 = (WIDTH);
  • int y1 = (HEIGHT);
  • int x2 = (WIDTH);
  • int y2 = (HEIGHT);
  • (x1, y1, x2, y2);
  • }
  • ();
  • return image;
  • }
  • }
  • 相关文章