c# 自己写验证码
2013-10-28 12:52
351 查看
效果
后台代码
前台调用
后台代码
protected override void OnPreInit(EventArgs e) { //字符 去掉了 o0 i1l string str = "A,B,C,D,E,F,G,H,G,K,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,2,3,4,5,6,7,8,9"; //颜色 Color[] cs = new Color[] { Color.Red, Color.Green, Color.Black, Color.Blue, Color.Purple }; //字体 string[] fs = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }; //字体大小 int[] size = new int[] { 16, 18, 20 }; //字体样式 FontStyle[] _fs = new FontStyle[] { FontStyle.Bold, FontStyle.Italic, FontStyle.Regular }; Random ram = new Random(); Bitmap img = new Bitmap(80, 25); Graphics g = Graphics.FromImage(img); //清空图片 g.Clear(Color.White); //画干扰线 for (int i = 1; i <= 5; i++) { int x1 = ram.Next(img.Width); int y1 = ram.Next(img.Height); int x2 = ram.Next(img.Width); int y2 = ram.Next(img.Height); Pen p = new Pen(cs[ram.Next(cs.Length)]); g.DrawLine(p, x1, y1, x2, y2); } //画字符 string[] array = str.Split(','); string vcode = string.Empty; for (int i = 1; i <= 4; i++) { Font f = new Font(fs[ram.Next(fs.Length)], size[ram.Next(size.Length)], _fs[ram.Next(_fs.Length)]); Brush b = new SolidBrush(cs[ram.Next(cs.Length)]); string temp = array[ram.Next(array.Length)]; vcode += temp.ToLower(); if (ram.Next(9) % 2 == 0) { g.DrawString(temp, f, b, new Point(20 * (i - 1) + 0, 0)); } else { g.DrawString(temp.ToLower(), f, b, new Point(20 * (i - 1) + 0, 0)); } } //画噪点 for (int i = 1; i <= 30; i++) { int x = ram.Next(img.Width); int y = ram.Next(img.Height); Color clr = cs[ram.Next(cs.Length)]; img.SetPixel(x, y, clr); } //将验证码的值保存 Response.Cookies.Add(new HttpCookie("9FDFFFADBEF1A3D9612D39754765D442", StringHelper.EncryptAES(vcode))); //设置页面无缓存 Response.Buffer = true; Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1); Response.Expires = 0; Response.CacheControl = "no-cache"; Response.AppendHeader("Pragma", "No-Cache"); //写入文件流 System.IO.MemoryStream ms = new System.IO.MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); Response.Cache.SetNoStore(); Response.ClearContent(); Response.ContentType = "image/Jpeg"; Response.BinaryWrite(ms.ToArray()); //释放 g.Dispose(); img.Dispose(); Response.End(); }
前台调用
<img src="VCode.aspx" alt="看不清,换一个" title="看不清,换一个" style="cursor:pointer;" onclick="javascript:this.src='VCode.aspx?vc='+Math.random();" />
相关文章推荐
- Unity3D 双摇杆 c# JoyStick 实现自己的双摇杆
- C#.Net 较完美随机验证码
- ASP.net 验证码(C#)
- ASP.net 验证码(C#) MVC
- 从零开始编写自己的C#框架(3)——开发规范
- c#验证码
- C#中用Microsoft Agent为自己的程序创建精灵助手
- 用C#生成随机中文汉字验证码的基本原理
- 使用C#开发百度空间验证码自动填写的工具
- C#实现Dll(OCX)控件自动注册的两种方法 网上找的 然后 自己试了试 还是可以用的
- 打造自己的c#屏幕保护程序(,源码)
- 自己总结的C#通用方法(收藏)
- Asp.net(C#)实现验证码功能
- C#基础系列:实现自己的ORM(反射以及Attribute在ORM中的应用)
- C#生成随机验证码代码分享
- 用C#生成随机中文汉字验证码的基本原理
- 自己动手用c#写控件(下)
- 【转】C# 获取网页验证码
- [转]asp.net(c#)生成验证码 点击可刷新
- C#捕获windows关机事件,在系统关机前做一些自己想做的事