package web;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/random.action")
public class CheckCodeServlet extends HttpServlet {
Random random = new Random();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int width = 90;
int height = 25;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
g.fillRect(0, 0, image.getWidth(), image.getHeight());//图片大小
g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字体大小
g.setColor(getRandColor(110, 133));
//绘制干扰线
for (int i = 0; i < 10; i++) {
int x = random.nextInt(image.getWidth());
int y = random.nextInt(image.getHeight());
int xl = random.nextInt(13);
int yl = random.nextInt(13);
g.drawLine(x, y, x + xl, y + yl);
}
String randString = "0123456789ABCDEHGHIJKLMNOPQRSTUVWXYZ";
for (int i = 1; i <= 4; i++) {
g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
g.setColor(new Color(random.nextInt(101), random.nextInt(111),
random.nextInt(121)));
int index = random.nextInt(randString.length());
char ch = randString.charAt(index);
g.drawString(ch+"",13* i , 16);
}
ImageIO.write(image, "JPEG", resp.getOutputStream());
}
private Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc - 16);
int g = fc + random.nextInt(bc - fc - 14);
int b = fc + random.nextInt(bc - fc - 18);
return new Color(r, g, b);
}
}