GDI+生成验证码

来源:未知 责任编辑:智问网络 发表时间:2013-11-12 17:20 点击:
Register.aspx
 
// 当点击验证码图片时,自动重新导向一次authcode.aspx,就重新刷新一次验证码
$('#authimage').click(function() {
$(this).attr("src", "authcode.aspx");
 });
 
 
验证码:<input id="authcode" type="text" class="required" name="authcode" />
<img src="authcode.aspx" width="60px" height="30px" style="cursor:pointer" id="authimage"/>
注意,这个验证码图片的路径是一个动态页面!我们就在这个动态页面中利用GDI+技术绘制出验证码
 
authcode.cs
public partial class authcode : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // 验证码中可能出现的字符
            string authCodeString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            // 验证码字符集合长度
            int length = authCodeString.Length;
            // 绘制字符字体
            Font f = new Font("宋体", 24, FontStyle.Bold);
            // 绘制验证码的画刷对象
            Brush b = null;
            // 绘制验证码的颜色
            Color brushColor = new Color();
            Bitmap image = new Bitmap(80, 40);
            Graphics g = Graphics.FromImage(image);
            g.Clear(Color.Gray);// 设置背景
           
            string authCode = string.Empty;// 整个显示给用户的验证码
            string code = string.Empty;    // 当前绘制的验证码
            Random random = new Random();
            for (int i = 0; i < 4; i++)
            {
                // 取余保证current长度不会超过验证码字符集合长度
                int current = random.Next((DateTime.Now.Millisecond) % length);
              
                // 验证码字符集合任意截取一个字符
                code = authCodeString.Substring(current, 1);
                authCode += code;
                brushColor = Color.FromArgb(random.Next(255), random.Next(255), random.Next(255));
                b = new SolidBrush(brushColor);
              
                // 绘制刚刚得到的字符串
                g.DrawString(code, f, b, i * 15, 2);
            }
            Response.Clear();
            Response.ContentType = "image/pjpeg";
            // 将对象保存到Response输出流中
            image.Save(Response.OutputStream, ImageFormat.Jpeg);
            image.Dispose();
            Session["authCode"] = authCode; // 在服务器端保存验证码,用来比较
            Response.End();
        }
    }

摘自 徐越的专栏
    发表评论
    请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
    用户名: 验证码:点击我更换图片
    最新评论 更多>>

    推荐热点

    • 浅析.NET下XML数据访问新机制
    • asp.net 面试+笔试题目第1/2页
    • C# 邮件地址是否合法的验证
    • asp.net 设置GridView的选中行的实现代码
    • C#高级编程:数据库连接[1]
    • 经典C++程序1
    • IIS 自动回收导致后台定时器失效的问题解决
    • ASP.NET&#160;GridView列表代码示例
    • Asp.net MVC源码分析--Action Filter的链式调用
    网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
    Copyright © 2008-2015 计算机技术学习交流网. 版权所有

    豫ICP备11007008号-1