protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;Chartset=utf-8");
//使用java的图形界面技术绘制一张图片
int charNum = 4;
int width = 20 * 4;
int height = 28;
//创建一张内存图片
BufferedImage image = new BufferedImage(width, height, charNum);
//获得绘图对象
Graphics graphics = image.getGraphics();
//绘制背景颜色
graphics.setColor(Color.CYAN);
graphics.fillRect(0,0,width,height);
//绘制边框
graphics.setColor(Color.MAGENTA);
graphics.drawRect(0,0,width-1,height-1);
//输出验证码内容
graphics.setColor(Color.black);
graphics.setFont(new Font("微软雅黑",Font.BOLD,22));
//随机输出4个字符
String s = "ABCDEFGHGKLMNPQRSTUVWXYZ23456789";
Random random = new Random();
String msg = "";
int x = 5;
for (int i = 0; i < charNum; i++) {
int index = random.nextInt(32);
String c = String.valueOf(s.charAt(index));
msg += c;
graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
graphics.drawString(c,x,22);
x += 20;
}
//绘制干扰线
graphics.setColor(Color.gray);
for (int i = 0 ; i < 5 ; i ++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1,y1,x2,y2);
}
//释放图片资源
graphics.dispose();
//输出图片
ImageIO.write(image, "jpg", response.getOutputStream());
}
java动态生成验证码
最新推荐文章于 2022-12-28 17:16:07 发布