自定义验证码方法

1:第一步,自定义一个数组方法

      

  public void CateGory() {

 

        string []code = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "A", "B", "C", "D", "E", "E", "F", "G", "H", "I", "J", "1", "2", "3", "4", "5", "6", "7", "8", "0", "9"};

    //随机

        Random randow = new Random();

        for (int i = 0; i < 5; i++)//生成5位数的验证码

        {

            result+=code[randow.Next(0,code.Length)];//将验证码数字加到变量中

        }

        

    }

 public string result;//申明接收验证码的变量


2:画出验证码保存为图片

public void DrawCode(HttpContext hc) {

        Random randow = new Random();

        Image img = new Bitmap(100,30);//准备画布

        Graphics gr=Graphics.FromImage(img);//绘制GID精灵

        

        Pen p = new Pen(Color.Black,1);//画笔;第一个参数表示画笔的颜色,第二个参数画笔的宽度

        gr.DrawRectangle(p, 0, 0, 100, 30);//绘制矩形

        gr.Clear(Color.White);//清空画布

        

        

        //画出验证码

        for (int i = 0; i < result.Length; i++)

        {

            gr.DrawString(result[i].ToString(),new Font ("微软雅黑",15),new  SolidBrush(Color.FromArgb(randow.Next(0,100),randow.Next(0,100),randow.Next(0,100))),i*20,randow.Next(0,5));

            gr.DrawLine(p, randow.Next(0, 40), randow.Next(0, 25), randow.Next(40, 80), randow.Next(0, 25));

        }

  Brush dot = new SolidBrush(Color.Blue);

            //画点

            for (int i = 0; i < 100; i++)

            {

                gr.FillEllipse(dot, randow.Next(0, 80), randow.Next(0, 25), 2f, 2f);

            }

 

        

        

       hc.Response.ContentType = "image/jpeg";// 更换宣布渲染格式

       img.Save(hc.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); //保存渲染结果,图片

}  

.Ashx输出验证码;

   public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "image/gif";

        CateGory();

        DrawCode(context);

}   

3:前台展示:

  <img src="Code/CodeImage.ashx" id="img"/><a href="#" id="qi" onclick="ss();">点击切换</a>

  <script>

       function ss() {

           document.getElementById('img').src = "Code/CodeImage.ashx?d=" + Math.random();

           //点击切换验证码

       }

   </script>


是是 水水

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值