如何生成验证码的java实现

/**
     * 生成所需要的图片
     * @param _request
     * @param _response
     * @throws ServletException
     * @throws IOException
     */
    public void doGet(HttpServletRequest _request, HttpServletResponse _response) throws ServletException,IOException
    {
        //获得参数
        String _bgColor    = _request.getParameter("bgcolor");
        String _frontColor = _request.getParameter("frontcolor");

        if((_bgColor == null) || _bgColor.trim().equals(""))
            _bgColor = "#FFFFFF";
        else
            _bgColor = "#" + _bgColor;
        if((_frontColor == null) || _frontColor.trim().equals(""))
            _frontColor = "#000000";
        else
            _frontColor = "#" + _frontColor;

        // 获得一个认证码
        String _authSnCode = Daemon.getAuthCode() ;

        if (_authSnCode != null)
        {
            //得到authsn,authcode
            int _length = _authSnCode.indexOf(":");
            String _authsn = _authSnCode.substring(0,_length);
            String _authcode = _authSnCode.substring(_length + 1);
            //把authsn放入session中
            HttpSession _session = _request.getSession();
            _session.setAttribute("authsn",_authsn);
            //把authcode输入
            BufferedImage _image = new BufferedImage(52,20,BufferedImage.TYPE_INT_RGB);
            Graphics _graphics = _image.getGraphics();
            _graphics.setColor(Color.decode(_bgColor) );
            _graphics.fillRect(0,0,52,20);
            _graphics.setFont(new Font("Times-Roman",Font.BOLD ,15));
            _graphics.setColor(Color.decode(_frontColor) );
            _graphics.drawString(_authcode,1,14);

            _response.setHeader("Cache-Control","no-store");
            _response.setContentType("image/jpeg");

            ServletOutputStream _out = _response.getOutputStream();
            // Use a separate stream to encode the image
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bout);
            encoder.encode((BufferedImage)_image);
            // Write image to client
            bout.writeTo(_out);
            _out.flush();
            _out.close();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值