生成验证码

主要是在一个BufferedImage上画上验证码,然后使用ImageIO将图片通过响应输出流输出到页面

        int width=100;
        int height=35;

        BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g=bi.getGraphics();
        Random random=new Random();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,width,height);

        Font font=new Font("Times NewRoman",Font.PLAIN,30);
        g.setFont(font);
        g.setColor(Color.BLACK);
        g.drawRect(0,0,width-1,height-1);

        g.setColor(Color.GRAY);
//画划痕
        for(int i=0;i<160;i++){
            int x=random.nextInt(width);
            int y=random.nextInt(height);
            int x1=random.nextInt(20);
            int y1=random.nextInt(20);
            g.drawLine(x,y,x1+x,y1+y);
        }
//产生一个验证码,见下一个代码快
        String validateCode= ToolUtil.validateCode(4, 2);
        int red=0,green=0,blue=0;
        for(int i=0;i<4;i++){
            red=random.nextInt(110);
            green=random.nextInt(50);
            blue=random.nextInt(50);

            g.setColor(new Color(red,green,blue));
            g.drawString(String.valueOf(validateCode.charAt(i)),20*i+6,25);
        }

        session.setAttribute("imgcode",validateCode);

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream sos=null;
        try {
            sos=response.getOutputStream();
            ImageIO.write(bi, "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
		if (sos != null) {
		    try {
                        sos.close();
                    } catch (IOException e) {
                    }
	        }
        }
/**
     * way  1代表只有数字  2代表数字加字母
     * num代表数量
     * @param num
     * @param way
     * @return
     */
    public static String validateCode(int num,int way){
        String code="0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
        int max;
        char ch;
        StringBuffer validateCode=new StringBuffer();
        ThreadLocalRandom random=ThreadLocalRandom.current();
        if(way==1){
            max=10;
        }else{
            max=62;
        }

        for(int i=0;i<num;i++){
            ch=code.charAt(random.nextInt(0,max));
            validateCode.append(ch);
        }

        return validateCode.toString();
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值