@WebServlet("/VerificationCode")
public class VerificationCode extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
输出随机图片(CAPTCHA图像):
Completely Automated Public Turing Test to Tell Computers and Humans Apart
(全自动区分计算机和人类的测试)
相关主要类(JDK 查看API)
BufferedImage:内存图像
Graphics:画笔
ImageIO:输出图像
*/
//1.创建BufferedImage对象
int width = 120;
int height = 30;
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
//2.获取Graphics对象
Graphics g = bi.getGraphics();
//3.添加背景颜色
g.setColor(Color.PINK);
g.fillRect(0, 0, width, height);
//4.绘制干扰线
Random r = new Random();
for (int i = 0; i < 4; i++) {
changeColor(i, g);
//第一个点
int x1 = r.nextInt(width);
int y1 = r.nextInt(height);
//第二个点
int x2 = r.nextInt(width);
int y2 = r.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
//5.绘制数字
int left = 15;
for (int i = 0; i < 4; i++) {
int num = r.nextInt(10);
changeColor2(i, g);
g.drawString(num + "", left + i * 25, 20);
}
//6.输出图片,设置响应格式
resp.setContentType("image/jpeg");
ImageIO.write(bi, "JPEG", resp.getOutputStream());
}
public static void changeColor(int i, Graphics g) {
if (i == 0) {
g.setColor(Color.GREEN);
} else if (i == 1) {
g.setColor(Color.CYAN);
} else if (i == 2) {
g.setColor(Color.ORANGE);
} else {
g.setColor(Color.WHITE);
}
}
public static void changeColor2(int i, Graphics g) {
if (i == 0) {
g.setColor(Color.BLACK);
} else if (i == 1) {
g.setColor(Color.BLUE);
} else if (i == 2) {
g.setColor(Color.MAGENTA);
} else {
g.setColor(Color.YELLOW);
}
}
}