Java后端技术生成随机验证码图片
import java.awt.*;
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;
public class CaptchaGenerator {
private static final int WIDTH = 90;
private static final int HEIGHT = 30;
private static final int FONT_SIZE = 20;
public static void generate(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("image/png");
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, WIDTH, HEIGHT);
graphics.setFont(new Font("Arial", Font.BOLD, FONT_SIZE));
Random random = new Random();
StringBuilder captchaBuilder = new StringBuilder();
for (int i = 0; i < 4; i++) {
char captchaChar = (char) (random.nextInt(26) + 'A');
captchaBuilder.append(captchaChar);
graphics.setColor(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat()));
graphics.drawString(String.valueOf(captchaChar), i * 20 + 10, HEIGHT - (HEIGHT - FONT_SIZE) / 2);
}
request.getSession().setAttribute("captcha", captchaBuilder.toString());
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image, "png", outputStream);
outputStream.flush();
outputStream.close();
}
}