Java Web实现一个简易的验证码

Java实现简易验证码

使用Java 的 图片IO流对象 ,实现一个在一个图片对象的基础上进行 写字符串, 画像, 等

@WebServlet("/checkcode")
public class CheckCode extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Image对象的高度和宽度
		int width = 100;
		int height = 50;
		
		//1.创建一对象,在内存中图片(验证码图片对象): 默认使用黑色进行填充
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		
		//3.填充图片
		//获取画笔对象: 画笔用来进行填充,画画, 写字符串
		final Graphics graphics = image.getGraphics();
		//设置画笔颜色
		graphics.setColor(Color.ORANGE);
		//填充颜色
		graphics.fillRect(0,0,width-1 , height-1);
		
		//画边框
		graphics.setColor(Color.blue);
		graphics.drawRect(0,0,width - 1, height - 1);
		
		//随机字符串: 进行随机验证码的字符串
		String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
		//随机颜色: Color 类的一些常用变量
		Color[] colors = {Color.BLACK , Color.BLUE , Color.CYAN , Color.DARK_GRAY , Color.GRAY , Color.GREEN , Color.MAGENTA , Color.ORANGE, Color.RED, Color.WHITE , Color.WHITE , Color.PINK} ;
		
		//写验证码
		Random random = new Random();
		int index = 0 ;
		//写4个字符
		for (int i = 1; i <= 4; i++) {
			//获取下标
			index = random.nextInt(str.length());
			//随机颜色: 
			graphics.setColor(colors[random.nextInt(colors.length)]);
			//写验证码: 在图片上写字符
			graphics.drawString(""+str.charAt(index), width /5 * i, height / 2);
		}
		//画干扰线
		for (int i = 0; i < 10 ; i++) {
			//起始坐标
			int x1 = random.nextInt(width);
			int x2 = random.nextInt(width);

			//结束坐标
			int y1 = random.nextInt(height);
			int y2 = random.nextInt(height);
			//设置划线颜色
			graphics.setColor(colors[random.nextInt(colors.length)]);
			graphics.drawLine(x1 ,y1 , x2 , y2);
		}

		//3.将图片输出到页面展示: 输出源, 输出图片格式, 输出流
		ImageIO.write(image,"jpg",response.getOutputStream());

	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request,response);
	}

}

程序代码实现了, 随机字符, 随机字符颜色, 随机线条, 随机线条颜色, 随机位置的要求, 总结一下步骤:

  1. 创建一个图片buffer 对象。用来存放图片, 将图片对象放置在内存中
  2. 填充图片: 填充背景颜色, 边框等
  3. 在图片中写入一个字符
  4. 在图片中画一条线
  5. 在图片中随机写4个字符
  6. 在图片中画一定数量的线条
  7. 使线条起始,结束位置随机, 字符随机位置排列

如果在创建出来的图片无法在页面中显示, 请尝试使用IE, 火狐等浏览器 ,
效果图:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值