@WebServlet(name = "Demo10Servlet", urlPatterns = "/vcode")
public class Demo10Servlet extends HttpServlet {
//创建随机对象
private Random ran = new Random();
// 写一个方法随机获取颜色
public Color getRanColor() {
int r = ran.nextInt(256);
int b = ran.nextInt(256);
int g = ran.nextInt(256);
return new Color(r, b, g);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 创建缓存图片:指定宽width=90,高height=30
int width = 90;
int height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取画笔对象
Graphics graphics = image.getGraphics();
// 设置画笔颜色,并且填充矩形区域
graphics.setColor(Color.white);//设置背景为白色
//并且设置填充矩形区域
graphics.fillRect(0, 0, width, height);
// 从字符数组中随机得到字符
char[] arr = {'A', 'B', 'C', 'D', 'J', 'U', 'N', 'G', 'A', 'N', '1', '2', '3', '4'};
//设置循环,得到四个数
for (int i = 0; i < 4; i++) {
//得到索引
int index = ran.nextInt(arr.length);
//取出一个字符
char c = arr[index];
// 设置字体,大小为18,设置字的颜色随机
graphics.setFont(new Font(Font.DIALOG, Font.BOLD + Font.ITALIC, 19));
//设置背景颜色
graphics.setColor(getRanColor());
//把字符转成字符串
// 将每个字符画到图片,位置:5+(i*20), 20
graphics.drawString(String.valueOf(c), 10 + (i * 20), 20);
}
// 画干扰线8条线,线的位置是随机的,x范围在width之中,y的范围在height之中。
for (int i = 0; i < 8; i++) {
graphics.setColor(getRanColor());
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
graphics.drawLine(x1, y1, x2, y2);
}
// 将缓存的图片输出到响应输出流中
ImageIO.write(image, "jpg", response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
网页验证码的绘制模板(Java)
最新推荐文章于 2024-01-13 23:54:18 发布