自己动手用写简单的验证码(JAVA)
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
private static final int WIDTH = 100;
private static final int HEIGHT = 50;
private static final int NUMBEROF_CODES = 4;
private static final int NUMBEROF_LINES = 7;
private static final int FONTSIZE = 16;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 创建图像
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR);
// 获取画笔对象
Graphics pointer = image.getGraphics();
// 填充验证码矩形图像的背景色
pointer.setColor(Color.BLACK);
pointer.fillRect(0, 0, WIDTH, HEIGHT);
// 绘制边框
pointer.setColor(Color.YELLOW);
pointer.drawRect(0, 0, WIDTH -1, HEIGHT -1);
// 准备待展示验证码字符集和颜色
pointer.setColor(Color.WHITE);
String codeSet = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
// 将验证码绘制在矩形里,并存下字符串值
Random ran = new Random();
int last = WIDTH / (NUMBEROF_CODES * 2);
StringBuffer sb = new StringBuffer();
for(int i = 0; i < NUMBEROF_CODES; i++) {
char ch = codeSet.charAt(ran.nextInt(codeSet.length()));
pointer.setFont(new Font("verdana", Font.BOLD, FONTSIZE));
pointer.drawString(ch+"",
last = ran.nextInt(WIDTH) / NUMBEROF_CODES + last,
ran.nextInt((NUMBEROF_CODES - 1) * HEIGHT / NUMBEROF_CODES) + HEIGHT / NUMBEROF_CODES);
sb.append(ch);
}
// 设置干扰线
pointer.setColor(Color.PINK);
for(int i = 0; i < NUMBEROF_LINES; i++) {
int x1 = ran.nextInt(WIDTH), y1 = ran.nextInt(HEIGHT);
int x2 = ran.nextInt(WIDTH), y2 = ran.nextInt(HEIGHT);
pointer.drawLine(x1, y1, x2, y2);
}
// 将图片输出到页面展示
ImageIO.write(image, "jpg", resp.getOutputStream());
}
}
原文地址:https://www.cnblogs.com/fromneptune/p/12371546.html
时间: 2024-11-09 22:45:59