原理其实就是用java将随机生成的数字。

画到画板上。

把这几个字符,增强,斜体啥的。

最后增加干扰线即可。

 

程序运行截图如下:

输入错误后:

输入正确就可以进行跳转了

 

关键代码如下:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //1. 创建画板
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //2. 创建画板
        Graphics2D pen = img.createGraphics();

        //3. 生成随机内容
        String code = randCode(4);
        request.getSession().setAttribute("valiCode", code);

        //4. 绘制内容
        //  4.1 设置绘制区域
        pen.fillRect(0, 0, width, height);

        //  4.2 设置字体
        pen.setFont(new Font("微软雅黑", Font.BOLD, fontsize + random.nextInt(5)));

        //  4.3 按顺序逐个绘制字符
        for(int i = 0; i < code.length(); i++){

            pen.setColor(randColor());
            pen.drawString(code.charAt(i) + "", 5 + i * fontsize, (fontsize + height) / 2 + random.nextInt(5));
        }

        //  4.4 绘制噪音线
        for(int i = 0; i < 3; i++){

            pen.setColor(randColor());
            pen.setStroke(new BasicStroke(3));
            pen.drawLine(random.nextInt(width / 2), random.nextInt(height), random.nextInt(width), random.nextInt(height));
        }

        //5.保存图片并发送
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(img, "png", out);
        out.flush();
        out.close();
    }

源码打包下载地址:

https://github.com/fengfanchen/Java/tree/master/vailSampleDemo

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐