验证码

作者: JayMeWangGL | 来源:发表于2019-11-01 16:15 被阅读0次

    首先创建图片对象

    设置好图片的宽度100和高度50
    使用 BufferedImage创建图片对象

    @WebServlet("/YanZhengServlet")
    public class YanZhengServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            int width  = 100;
            int height = 50;
            BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
    
            //将验证码输出到页面
            ImageIO.write(image,"jpg",response.getOutputStream());
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
    }
    

    其次设置验证码的背景色

    步骤:
    1、获取画图工具对象Graphics g = image.getGraphics();
    2、设置颜色 g.setColor(Color.PINK);
    3、进行背景填充g.fillRect(0,0,width,height);

            Graphics g = image.getGraphics();
            g.setColor(Color.PINK);
            g.fillRect(0,0,width,height);
    

    设置显示验证码

            g.setColor(Color.MAGENTA);
            g.drawString("A",20,25);
            g.drawString("B",40,25);
            g.drawString("C",60,25);
            g.drawString("D",80,25);
    
    效果展示:
    进阶操作:随机生成验证码

    首先将字母大小写和数字都存在一个字符串中,然后随机生成一个index,获取对应的字符。再写入到验证码图片中。

            String S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
            for (int i = 1; i <= 4; i++) {
                Random random = new Random();
                int index = random.nextInt(S.length());
                char c = S.charAt(index);
                g.drawString(c+"",width/5*i,height/2);
            }
    
    Random

    混淆视觉(干扰线)

    绘制一些线段来模拟遮挡验证码的混淆视觉效果

            g.setColor(Color.GREEN);
            for (int i = 0; i < 10; i++) {
    
                Random random = new Random();
                int x1 = random.nextInt(width);
                int x2 = random.nextInt(width);
                int y1 = random.nextInt(height);
                int y2 = random.nextInt(height);
                g.drawLine(x1,x2,y1,y2);
            }
    

    效果展示:


    效果

    相关文章

      网友评论

          本文标题:验证码

          本文链接:https://www.haomeiwen.com/subject/extqbctx.html