Java后台画一个验证码

画一个验证码

在这里插入图片描述

创建一个文本word.txt,验证码库

在这里插入图片描述

创建一个前台,目的是为了点击二维码可以切换二维码;

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function code(jpg) {
		jpg.src = "/web03/responseCode?zz=" + new Date().getTime();
	}
</script>
</head>
<body>
	<img onclick="code(this)" src="/web03/responseCode" />
</body>
</html>

创建一个Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	//获得word.txt的路径
	String realPath = getServletContext().getRealPath("WEB-INF/word.txt");
	//创建一个集合
	List arrayList = new ArrayList();
	//使用字符缓冲流,readLine()读一行的方法
	BufferedReader bufferedReader = new BufferedReader(new FileReader(realPath));
	String readLine = bufferedReader.readLine();
	while (readLine != null) {
		arrayList.add(readLine);
		readLine = bufferedReader.readLine();
	}

	// 画一个验证码 随机验证码
	int height = 30;
	int width = 110;

	// 内存中 画一个图片
	BufferedImage bufferedImage = new BufferedImage(width, height,
			BufferedImage.TYPE_INT_RGB);

	// 画笔
	Graphics graphics = bufferedImage.getGraphics();

	// 给图片添加背景颜色
	graphics.setColor(Color.WHITE);
	graphics.fillRect(0, 0, width, height);
	// 边框
	graphics.setColor(Color.BLUE);
	graphics.drawRect(0, 0, width - 2, height - 2);
	// 写入验证码
	// 设置字体
	graphics.setFont(new Font("楷体", Font.BOLD, 20));
	Random random = new Random();

	Graphics2D graphics2D = (Graphics2D) graphics;
	//从arrayList集合中随机取出一行数据
	String mess = (String) arrayList.get(random.nextInt(arrayList.size()));

	graphics2D.setColor(new Color(random.nextInt(255), random.nextInt(255),
			random.nextInt(255)));

	// 弧度
	int jiaodu = random.nextInt(15) - 7;

	double theta = jiaodu * Math.PI / 180;

	graphics2D.rotate(theta, (width / 6), 20);

	graphics2D.drawString(mess, (width / 7), 22);

	graphics2D.rotate(-theta, (width / 6), 20);

	// 画干扰线
	for (int i = 0; i < 5; i++) {
		graphics2D.setColor(new Color(random.nextInt(255), random
				.nextInt(255), random.nextInt(255)));
		graphics2D.drawLine(random.nextInt(width), random.nextInt(height),
				random.nextInt(width), random.nextInt(height));
		graphics2D.drawOval(random.nextInt(width), random.nextInt(height),
				2, 3);

	}

	// 给客户端响应图片
	ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值