图片验证《全自动》

工具类

package com.bawei.uti;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 验证码生成器
 *
 * @author
 */
public class ValidateCode {
   
    // 图片的宽度。
    private int width = 160;
    // 图片的高度。
    private int height = 40;
    // 验证码字符个数
    private int codeCount = 5;
    // 验证码干扰线数
    private int lineCount = 150;
    // 验证码
    private String code = null;
    // 验证码图片Buffer
    private BufferedImage buffImg = null;

    // 验证码范围,去掉0(数字)和O(拼音)容易混淆的(小写的1和L也可以去掉,大写不用了)
    private char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    /**
     * 默认构造函数,设置默认参数
     */
    public ValidateCode() {

      
        this.createCode();
    }

    /**
     * @param width  图片宽
     * @param height 图片高
     */
    public ValidateCode(int width, int height) {
        System.out.println("----------1");
        this.width = width;
        this.height = height;
        this.createCode();
    }

    /**
     * @param width     图片宽
     * @param height    图片高
     * @param codeCount 字符个数
     * @param lineCount 干扰线条数
     */
    public ValidateCode(int width, int height, int codeCount, int lineCount) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        this.lineCount = lineCount;
        this.createCode();
    }

    public void createCode() {
        int x = 0, fontHeight = 0, codeY = 0;
        int red = 0, green = 0, blue = 0;

        x = width / (codeCount + 2);//每个字符的宽度(左右各空出一个字符)
        fontHeight = height - 2;//字体的高度
        codeY = height - 4;

        // 图像buffer
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();
        // 生成随机数
        Random random = new Random();
        // 将图像填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        // 创建字体,可以修改为其它的
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
//        Font font = new Font("Times New Roman", Font.ROMAN_BASELINE, fontHeight);
        g.setFont(font);

        for (int i = 0; i < lineCount; i++) {
            // 设置随机开始和结束坐标
            int xs = random.nextInt(width);//x坐标开始
            int ys = random.nextInt(height);//y坐标开始
            int xe = xs + random.nextInt(width / 8);//x坐标结束
            int ye = ys + random.nextInt(height / 8);//y坐标结束

            // 产生随机的颜色值,让输出的每个干扰线的颜色值都将不同。
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);
            g.setColor(new Color(red, green, blue));
            g.drawLine(xs, ys, xe, ye);
        }

        // randomCode记录随机产生的验证码
        StringBuffer randomCode = new StringBuffer();
        // 随机产生codeCount个字符的验证码。
        for (int i = 0; i < codeCount; i++) {
            String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
            // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);
            g.setColor(new Color(red, green, blue));
            g.drawString(strRand, (i + 1) * x, codeY);
            // 将产生的四个随机数组合在一起。
            randomCode.append(strRand);
        }
        // 将四位数字的验证码保存到Session中。
        code = randomCode.toString();
    }

    public void write(String path) throws IOException {
        OutputStream sos = new FileOutputStream(path);
        this.write(sos);
    }

    public void write(OutputStream sos) throws IOException {
        ImageIO.write(buffImg, "png", sos);
        sos.close();
    }

    public BufferedImage getBuffImg() {
        return buffImg;
    }

    public String getCode() {
        return code;
    }
}

action

@RequestMapping("toValidateCode")
	@ResponseBody
	public String toValidateCode(HttpServletResponse response,HttpSession session)throws Exception{
		ValidateCode vCode = new ValidateCode(160,40,5,150);
		// 设置响应的类型格式为图片格式
		response.setContentType("image/jpeg");
		//禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		vCode.write(response.getOutputStream());
		System.out.println(vCode.getCode().toString());
		
		session.setAttribute("code",vCode.getCode().toString());
		return null;
		 
	}
	/*
	ajax验证验证码是否输入正确
	 */
	@RequestMapping("yzCode")
	@ResponseBody
	public String yzCode(String code,HttpSession session){
		String codel = (String)session.getAttribute("code");
		if(code.equalsIgnoreCase(codel)){
			System.out.println("验证成功");
			return "1";
		}
		System.out.println("验证失败");
		return "0";
	}

jsp

<html><head>
    <meta charset="UTF-8">
   
    <meta http-equiv="mobile-agent" content="format=wml; url=http://m.qidian.com">
    <meta http-equiv="mobile-agent" content="format=xhtml; url=http://m.qidian.com">
    <meta http-equiv="mobile-agent" content="format=html5; url=http://h5.qidian.com/bookstore.html">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta name="renderer" content="webkit">
    <title>图片雁阵给</title>
    <link rel="stylesheet" type="text/css" href="https://sta.gtimg.com/c/=/qd2/css/cssreset.css,/qd2/css/header.css,/qd2/css/login.css,/qd2/css/layout.css,/qd2/css/sprites.css,/qd2/css/ui.css,/qd2/css/footer.css,/qd2/css/font.css,/qd2/css/reg.css,/qd2/css/pact.css">
    <link rel="shortcut icon" type="image/x-icon" href="//qidian.gtimg.com/qd/favicon/qd_icon.0.2.ico">
    <link rel="Bookmark" type="image/x-icon" href="//qidian.gtimg.com/qd/favicon/qd_icon.0.2.ico">


    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  
        /*验证码验证*/
        function yzcode(){
            var val = $("#txtphoneimgcode").val();
            $.post("yzCode",{code:val},function(data){
                if(data=="1"){
                   
                    code=1;
                }else {
                    $("#mess").html("<font color='green'>验证错误</font>");
                    code=0;
                }
            })
            yzAll()
        }
       
        /*验证密码不为空*/
        function yzPassword(){
            var yzpassword = $("#txtphonepwd").val();
            if(yzpassword.trim()!=""){
                // alert("password true")
                password=1;
            }else {
                password=0;
            }
            yzAll();
        }
        /*验证两次输入密码一致*/
        function yzPassword2(){
            var yzpassword = $("#txtphonepwd2").val();
            if(yzpassword.trim()!=""){
                //alert("password2 true")
                password1=1;
            }else {
                password1=0;
            }
            yzAll();
        }

    </script>
    <script src="https://sta.gtimg.com/c/=/qd/js/jquery-1.9.1.min.js,/qd/js/lulu/Checkbox.js,/js/front_login.js,/js/login_v2.js,/js/phoneAreaSortNew.js"></script>
    <script type="text/javascript">
        // 刷新图片
      
        function changeImg() {
            var imgSrc = $("#imgphonernd");
            var src = imgSrc.attr("src");
            var vartime=new Date().getTime();
            imgSrc.attr("src", src+"?vartime="+vartime);
        } 
        //为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
        function changeUrl(url) {
            var timestamp = (new Date()).valueOf();
            var index = url.indexOf("?",url);
            if (index > 0) {
                url = url.substring(0, url.indexOf(url, "?"));
            }
            if ((url.indexOf("&") >= 0)) {
                url = url + "×tamp=" + timestamp;
            } else {
                url = url + "?timestamp=" + timestamp;
            }
            return url;
        }
    </script>

</head>
<body>
<div class="wrap">
    <!-- start 头部 -->
    <div class="header reg-header qidian">
        <div class="box-center">
            <div class="logo cf"><a href="http://www.qidian.com"></a><em></em><span class="lang">用户注册</span></div>
        </div>
    </div>
    <!-- end 头部 -->
    <!-- start 整体居中 -->
    <div class="box-center">
        <!-- start 注册模块 -->
        <div class="reg-wrap">
            <!-- start 注册进度 -->
            <div class="reg-step">
                <!-- 步进到哪一步,就给当前span上class:act -->
                <span class="lang act"><i>1</i>填写注册信息</span>
                <span class="lang"><em class="iconfont"></em>注册成功</span>
            </div>
            <div class="reg-form-wrap">
                <form action="../user/saveUser">
                    <div class="reg-form-list form-list">
                        <dl>
                            <dd class="top" id="phone"><em>手机号</em>
                                <input class="mid" name="phone" type="text" placeholder="输入手机号码" id="txtphonenumberl" onblur="yzphone()">
                            </dd>
                           <dd id="imgphonernd_code"><em>验证码</em><input class="mid" type="text" id="txtphoneimgcode" placeholder="验证码" onblur="yzcode()"><img class="code-img" id="imgphonernd"  src="toValidateCode" alt="这里是验证码"><a  onclick="changeImg()" id="refresh_code" class="stat" data-stat="qd_L08|手机-验证码换一张|3" style="cursor:hand"  >换一张 <div id="mess"></div></a></dd>
                           <a class="error-tip">验证码错误</a>
                            <dd id="phonecode"><em>短信验证</em>
                                <input type="text" id="phones" class="mid" placeholder="输入验证码" onblur="yzPhoneCode()" >
                                <a class="get-code stat" onclick="toPhone(),settime(this)" id="get_code"  data-stat="qd_L09|获取验证码|3" style="cursor:hand">获取验证码</a>
                            </dd><dd id="phonepwd"><em>密码</em><input type="password" name="password" onblur="yzPassword()" id="txtphonepwd" placeholder="6-18位大小写字母、符号或数字">
                            <div class="password-tip" style="display:none">
                                <span><cite></cite></span>
                                <p id="pwdrule1">长度为6-18个字符</p>
                                <p id="pwdrule2">不能是9位以下的纯数字</p>
                                <p id="pwdrule3">不能包含空格</p>
                            </div>
                            <div class="password-strong" style="display:none">
                                <!-- 以下3个 不会重复出现,目前3个一起出现造成的换行问题请无视 -->
                                <p style="display:none"><span class="level-1"><b></b></span>弱</p>
                                <p style="display:none"><span class="level-2"><b></b></span>中</p>
                                <p style="display:none"><span class="level-3"><b></b></span>强</p>
                            </div>
                        </dd>
                            <dd id="password2"><em>确认密码</em><input onblur="yzPassword2()" type="password" id="txtphonepwd2" placeholder="再次输入密码"></dd>
                        </dl>
                        <div class="deal">
                            <input type="checkbox" id="deal" name="checkbox" checked="">
                            <label for="deal" class="ui-checkbox"></label><label for="deal">我已阅读并同意</label><a href="https://passport.yuewen.com/pact.html?mobile=0" target="_blank">《用户服务协议》</a>
                        </div>
                        <button class="red-btn go-reg" type="submit" id="btnPhoneRegister" disabled="disabled" style="background-color: #7f7f7f">立即注册</button>
                        <a class="blue switch-reg stat" data-stat="qd_L10|切换成邮箱注册|3" href="reg.html?appid=10&amp;areaid=1&amp;target=iframe&amp;ticket=1&amp;auto=1&amp;autotime=30&amp;returnUrl=http%3A%2F%2Fwww.qidian.com&amp;type=2">切换成邮箱注册</a>
                    </div>
                </form>
            </div>
            <!-- end 注册进度 -->
        </div>
        <!-- end 注册模块 -->
    </div>
    <!-- end 整体居中 -->
    <!--<script src="https://sta.gtimg.com/qd/js/jquery-1.9.1.min.js"></script>
    <script src="https://sta.gtimg.com/qd/js/lulu/Checkbox.js"></script>-->
    <script src="https://sta.gtimg.com/js/jquery.cookie.js"></script>
    <script src="https://sta.gtimg.com/js/yuewenauth.js"></script>
    <!-- <script src="https://sta.gtimg.com/js/phoneAreaSortNew.js"></script>-->
    <script src="https://sta.gtimg.com/js/register_v1.js"></script>
    <!-- <script src="https://sta.gtimg.com/qd/js/lulu/Select.js"></script>-->
    <script>
        var QRegister = new QRegister({"appId":10,"areaId":1,"auto":1,"autoTime":30,"source":"","version":"1","format":"jsonp","method":"","ticket":"1","target":"iframe","backUrl":"http:\/\/www.qidian.com","tab":"","apiUrl":"https:\/\/ptlogin.qidian.com","queryString":"appid=10&areaid=1&target=iframe&ticket=1&auto=1&autotime=30&returnUrl=http%3A%2F%2Fwww.qidian.com","type":1,"from":"qidian","isNeedShowYanbaPop":false,"ajaxdm":"","loginUrl":"login.html?appid=10&areaid=1&target=iframe&ticket=1&auto=1&autotime=30&returnUrl=http%3A%2F%2Fwww.qidian.com"});
        QRegister.force = 1;
        QRegister.showCaptcha();

    </script>

    <div class="footer">
        <div class="link">
            <a href="//www.qidian.com/about/intro" target="_blank">关于起点</a>
            <a href="//www.qidian.com/about/contact" target="_blank">联系我们</a>
            <a href="http://join.book.qq.com/index.html" target="_blank">加入我们</a>
            <a href="http://kf.qidian.com/Default.aspx" target="_blank">客服中心</a>
            <a href="http://bbs.qidian.com/list/53" target="_blank">提交建议</a>
            <a href="http://wwwploy.qidian.com/help/about_link.aspx" target="_blank">合作伙伴</a>
            <a href="http://www.qidian.com/helpcenter/default.aspx" target="_blank">使用指南</a>
            <a href="http://bbs.qidian.com" target="_blank">起点论坛</a>
            <a href="http://shop.qidian.com/Index.aspx" target="_blank">起点商城</a>
        </div>
        <p>Copyright (C) 2002-2016 www.qidian.com All Right Reserved版权所有 上海玄霆娱乐信息科技有限公司</p>
        <p>上海玄霆娱乐信息科技有限公司 增值电信业务经营许可证沪B2-20080046 沪网文[2012]0068-008 新出网证(沪)字010 沪ICP备08017520号-1</p>
        <p>请所有作者发布作品时务必遵守国家互联网信息管理办法规定,我们拒绝任何色情小说,一经发现,即作删除!客服电话:010-59357051</p>
        <p>本站所收录作品、社区话题、书库评论及本站所做之广告均属个人行为,与本站立场无关</p>
        <div class="safety-box">
            <div class="safety-img dib-wrap">
                <a class="site1" href="http://www.pdxa.cn/Welcome.Asp?Id=3101151112" target="_blank"></a><a class="site2" href="http://www.sgs.gov.cn/lz/licenseLink.do?method=licenceView&amp;entyId=20111011181417625" target="_blank"></a><a class="site3" href="http://www.cyberpolice.cn/wfjb" target="_blank"></a><a class="site4" href="https://ss.knet.cn/verifyseal.dll?sn=e12120411010037414000000&amp;pa=090993" target="_blank"></a><a class="site5" href="http://www.shjbzx.cn" target="_blank"></a><a class="site6" href="http://www.12377.cn/node_548446.htm" target="_blank"></a><a class="site7" href="http://www.12377.cn/" target="_blank"></a>
            </div>
            <p>起点正积极配合国家最新发布的《关于办理侵犯知识产权刑事案件适用法律若干问题的意见》,</p>
            <p>采用刑事手段进行严厉打击盗版,目前相关公安机关已经抓获犯罪嫌疑人15名!正告盗版网站立即停止侵权行为!</p>
        </div>
    </div></div>
<script src="https://qidian.gtimg.com/lbf/2.0.0/qidian/report.js"></script>
<script src="https://sta.gtimg.com/js/stat.js"></script>
<script>
    $(function () {
        Stat.init();
    });
</script>
</body></html>

 

转载于:https://my.oschina.net/u/3566463/blog/1517804

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值