阅读1007 返回首页    go 阿里云 go 技术社区[云栖]


Asp.net中GDI+生成验证码

Register.aspx
 
// 当点击验证码图片时,自动重新导向一次authcode.aspx,就重新刷新一次验证码
$('#authimage').click(function() {
$(this).attr("src", "authcode.aspx");
 });
 
 
验证码:<input type="text" name="authcode" />
<img src="authcode.aspx" width="60px" height="30px" />
注意,这个验证码图片的路径是一个动态页面!我们就在这个动态页面中利用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();
        }
    }

 

 

最后更新:2017-04-02 22:16:10

  上一篇:go 系统测试时有关日期和时间
  下一篇:go 照镜子 - 内功修炼