失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 如何生成随机验证码图片

如何生成随机验证码图片

时间:2022-07-02 15:32:22

相关推荐

如何生成随机验证码图片

一个简单的登录页面除了登录账号,密码,按钮等这些,想要显得复杂一些可以做一个验证码,防止机器人登录。

下面开始做一个验证码

1,新建一个class文件。

2,编写随机生成字符的方法

public static String randString(int count){ //count 生成字符的个数StringBuilder builder=new StringBuilder();String str="0123456789abcdefghijklnmpqrstuvwxy";Random rnd= new Random();for(int i=0;i<count;i++) {int pos = rnd.nextInt(str.length()); //从str 中生成一个随机数String s = str.substring(pos, pos + 1);builder.append(s);}return builder.toString();}

3,在CaptcheController文件中新建一个类,具体实现验证码的图片,主要用两个方法。还有更多的验证码编写的方法可以自己尝试。

public class CaptcheController extends HttpServlet{private final int WIDTH=100;private final int HEIGHT=20;protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {BufferedImage img= new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB); //申请内存空间,定义图片大小格式Graphics g= img.getGraphics();//定义画笔对象,g.setColor(Color.blue); //调用对象的方法,定义初始颜色g.fillRect(0,0,WIDTH,HEIGHT); //定义图片大小Font font= new Font("Algerian", Font.ITALIC, 18); //字体设置,大小,字体,g.setFont(font); //调用字体g.setColor(Color.orange); // 设置字符颜色String code= StrUtil.randString(4);HttpSession session=req.getSession(); //用session方式来储存密码session.setAttribute("code",code); //将随机生成的验证码 code,放到sessiong.drawString(code,30,15);//显示字体位置g.setColor(Color.black); //生成随机线for (int i=0; i<8; i++){Random random= new Random();int x=random.nextInt(WIDTH);int y=random.nextInt(HEIGHT);int x1=random.nextInt(WIDTH);int y1=random.nextInt(HEIGHT);g.drawLine(x,y,x1,y1);}g.setColor(Color.black); //生成燥点for (int i=0; i<100; i++){Random random1= new Random();int x=random1.nextInt(WIDTH);int y=random1.nextInt(HEIGHT);g.drawOval(x,y,1,1);}g.dispose();ServletOutputStream out = resp.getOutputStream(); //定义输出流ImageIO.write(img,"jpg",out); //图片是名字,格式是jpg,输出到outtry { //获取出现的异常out.flush(); //缓冲图片大小}finally{ //只执行下面的关闭out.close(); //关闭 write方法}}}

4,在登录界面获取验证码图片即可

String saveCode=(String) req.getSession().getAttribute("code"); //session 里有生成的验证码code,用getAttribute取出来

现在一个验证码的图片就可以显示出来了,图片的大小,字符的格式,还可以更改,(审美问题,图不好看,多多担待)

如果觉得《如何生成随机验证码图片》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。