通过servlet生成验证码

/**
 * 通过servlet的session和验证码个数,生成图片
 */
public class ImageUtil {
	private ImageUtil() {};
	private static final Random r = new Random();
	private static final int width = 148;
	private static final int height = 26;
	
	
	private static final char[] c= {
			'a','b','c','d','e','f','g','h','i','j',
			'k','l','m','n','o','p','q','r','s','t',
			'u','v','w','x','y','z',
			'0','1','2','3','4','5','6','7','8','9'
	};
	
	public static final BufferedImage createImage(HttpSession session, int length) {
		//根据宽高创建一张缓冲区图像, 图像使用的是正整数的RGB格式
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//从图像中获取画笔
		Graphics g = bi.getGraphics();
		//设置画笔颜色
		g.setColor(new Color(175,215,151));
		//使用画笔填充矩形,背景色
		setBackGround(g);
		//设置干扰线
		drowRandomLine((Graphics2D)g);
		StringBuilder sb = new StringBuilder();
		
		for(int i=0; i < length; i++) {			
			int index = r.nextInt(c.length);		
			sb.append(c[index]);
			//设置字体
			g.setFont(new Font("微软雅黑",Font.PLAIN,r.nextInt(5)+15));
			g.setColor(new Color(r.nextInt(200),r.nextInt(200),r.nextInt(200)));
			g.drawString(Character.toString(c[index]), (i+1)*20, 18);
		}
		//将验证码存入到session中
		session.setAttribute("sb", sb.toString());
		g.dispose();
		return bi;
	}
	
	
	/** 设置背景颜色 */
	private static void setBackGround(Graphics g) {
		//设置画笔颜色
		g.setColor(Color.white);
		//填充区域
		g.fillRect(0, 0, width, height);
	}
	
	/** 干扰线 */
	private static void drowRandomLine(Graphics2D g) {
		g.setStroke(new BasicStroke(0.3f));
		//设置线条数目, 线条颜色
			for(int i=0; i<3;i++) {
				//每次颜色随机
				g.setColor(new Color(r.nextInt(10),r.nextInt(10),r.nextInt(10)));
				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);
			}
	}	
	
}
/**
 * 验证码servlet
 *
 *
 */
public class CaptureServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//创建图像
		BufferedImage bi = ImageUtil.createImage(req.getSession(), 5);
		//以png格式   输出响应流到界面
		ImageIO.write(bi, "png", resp.getOutputStream());
		
		/** 设置浏览器不缓存图片*/
	       resp.setHeader("Cache-Control", "no-cache");
	       resp.setHeader("Pragma", "no-cache");
	       resp.setDateHeader("expires", -1);
	}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<img alt="验证码" src="capture">
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值