ASP.net 验证码(C#)

/* Copyright all(c) 2005 ZhongFeng, http://blog.csdn.net/SW515 */
 public class ValidateCode : System.Web.UI.Page
 {
  private void Page_Load(object sender, System.EventArgs e)
  {
   this.CreateCheckCodeImage(GenerateCheckCode());
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //

   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>

  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion

  private string GenerateCheckCode()
  {
   int number;
   char code;
   string checkCode = String.Empty;

   System.Random random = new Random();

   for(int i=0; i<5; i++)
   {
    number = random.Next();

    if(number % 2 == 0)
     code = (char)('0' + (char)(number % 10));
    else
     code = (char)('A' + (char)(number % 26));

    checkCode += code.ToString();
   }

   Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));

   return checkCode;
  }

  private void CreateCheckCodeImage(string checkCode)
  {
   if(checkCode == null || checkCode.Trim() == String.Empty)
    return;

   System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
   Graphics g = Graphics.FromImage(image);

   try
   {
    //生成随机生成器
    Random random = new Random();

    //清空图片背景色
    g.Clear(Color.White);

    //画图片的背景噪音线
    for(int i=0; i<25; i++)
    {
     int x1 = random.Next(image.Width);
     int x2 = random.Next(image.Width);
     int y1 = random.Next(image.Height);
     int y2 = random.Next(image.Height);

     g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
    }

    Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
    g.DrawString(checkCode, font, brush, 2, 2);

    //画图片的前景噪音点
    for(int i=0; i<100; i++)
    {
     int x = random.Next(image.Width);
     int y = random.Next(image.Height);

     image.SetPixel(x, y, Color.FromArgb(random.Next()));
    }

    //画图片的边框线
    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    Response.ClearContent();
    Response.ContentType = "image/Gif";
    Response.BinaryWrite(ms.ToArray());
   }
   finally
   {
    g.Dispose();
    image.Dispose();
   }
  }
 }


 

  假如以上验证码生成器页面名为:CheckCode.aspx,那么在登录页面中使用“<IMG>” 这个 HTML 元素来显示生成的验证码图片:<IMG src="CheckCode.aspx">
  在登录页面的登录按钮的处理事件中使用以下代码判断验证码:

  private void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
  {
   if(Request.Cookies["CheckCode"] == null)
   {
    lblMessage.Text = "您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。";
    lblMessage.Visible = true;
    return;
   }

   if(String.Compare(Request.Cookies["CheckCode"].Value, txtCheckCode.Text, true) != 0)
   {
    lblMessage.Text = "验证码错误,请输入正确的验证码。";
    lblMessage.Visible = true;
    return;
   }

        /*****    *****/

  }

  你可以使用或部分引用该段代码,不过必须保留以上版权注释部分内容,并注释代码来源,否则将保留追究侵权的权利!

 补充一个生成GIF图片的

jiewenxu (囧囧囧)    

namespace Kissogram.Common.Security
{
    using System;
    using System.IO;
    using System.Web;
    using System.Drawing;

    //GIF验证码类
    public class Validate
    {
        //设置最少4位验证码
        private byte TrueValidateCodeCount = 4;
        public byte ValidateCodeCount
        {
            get
            {
                return TrueValidateCodeCount;
            }
            set
            {
                //验证码至少为3位
                if (value > 4)
                    TrueValidateCodeCount = value;
            }
        }
        protected string ValidateCode = "";
        //是否消除锯齿
        public bool FontTextRenderingHint = false;
        //验证码字体
        public string ValidateCodeFont = "Arial";
        //验证码型号(像素)
        public float ValidateCodeSize = 13;
        public int ImageHeight = 23;
        //定义验证码中所有的字符
        public string AllChar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";

        //获得随机四位数
        private void CreateValidate()
        {
            ValidateCode = "";
            //将验证码中所有的字符保存在一个字符串数组中
            string[] CharArray = AllChar.Split(',');
            int Temp = -1;
            //生成一个随机对象
            Random RandCode = new Random();
            //根据验证码的位数循环
            for (int i = 0; i < ValidateCodeCount; i++)
            {
                //主要是防止生成相同的验证码
                if (Temp != -1)
                {
                    //加入时间的刻度
                    RandCode = new Random(i * Temp * ((int)DateTime.Now.Ticks));
                }
                int t = RandCode.Next(35);
                if (Temp == t)
                {
                    //相等的话重新生成
                    CreateValidate();
                }
                Temp = t;
                ValidateCode += CharArray[Temp];
            }
            //错误检测,去除超过指定位数的验证码
            if (ValidateCode.Length > TrueValidateCodeCount)
                ValidateCode = ValidateCode.Remove(TrueValidateCodeCount);
        }
        //生成一帧的BMP图象
        private void CreateImageBmp(out Bitmap ImageFrame)
        {
            //获得验证码字符
            char[] CodeCharArray = ValidateCode.ToCharArray(0, ValidateCodeCount);
            //图像的宽度-与验证码的长度成一定比例
            int ImageWidth = (int)(TrueValidateCodeCount * ValidateCodeSize * 1.3 + 4);
            //创建一个长20,宽iwidth的图像对象
            ImageFrame = new Bitmap(ImageWidth, ImageHeight);
            //创建一个新绘图对象
            Graphics ImageGraphics = Graphics.FromImage(ImageFrame);
            //清除背景色,并填充背景色
            //Note:Color.Transparent为透明
            ImageGraphics.Clear(Color.White);
            //绘图用的字体和字号
            Font CodeFont = new Font(ValidateCodeFont, ValidateCodeSize, FontStyle.Bold);
            //绘图用的刷子大小
            Brush ImageBrush = new SolidBrush(Color.Red);
            //字体高度计算
            int FontHeight = (int)Math.Max(ImageHeight - ValidateCodeSize - 3, 2);
            //创建随机对象
            Random rand = new Random();
            //开始随机安排字符的位置,并画到图像里
            for (int i = 0; i < TrueValidateCodeCount; i++)
            {
                //生成随机点,决定字符串的开始输出范围
                int[] FontCoordinate = new int[2];
                FontCoordinate[0] = (int)(i * ValidateCodeSize + rand.Next(1)) + 3;
                FontCoordinate[1] = rand.Next(FontHeight);
                Point FontDrawPoint = new Point(FontCoordinate[0], FontCoordinate[1]);
                //消除锯齿操作
                if (FontTextRenderingHint)
                    ImageGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
                else
                    ImageGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                //格式化刷子属性-用指定的刷子、颜色等在指定的范围内画图
                ImageGraphics.DrawString(CodeCharArray[i].ToString(), CodeFont, ImageBrush, FontDrawPoint);
            }
            ImageGraphics.Dispose();
        }
        //处理生成的BMP
        private void DisposeImageBmp(ref Bitmap ImageFrame)
        {
            //创建绘图对象
            Graphics ImageGraphics = Graphics.FromImage(ImageFrame);
            //创建铅笔对象
            Pen ImagePen = new Pen(Color.Red, 1);
            //创建随机对象
            Random rand = new Random();
            //创建随机点
            Point[] RandPoint = new Point[2];
            //随机画线
            for (int i = 0; i < 15; i++)
            {
                RandPoint[0] = new Point(rand.Next(ImageFrame.Width), rand.Next(ImageFrame.Height));
                RandPoint[1] = new Point(rand.Next(ImageFrame.Width), rand.Next(ImageFrame.Height));
                ImageGraphics.DrawLine(ImagePen, RandPoint[0], RandPoint[1]);
            }
            ImageGraphics.Dispose();
        }
        //创建GIF动画
        private void CreateImageGif()
        {
            Bitmap ImageFrame;
            Kissogram.Drawing.Gif.AnimatedGifEncoder GifPic = new Kissogram.Drawing.Gif.AnimatedGifEncoder();
            MemoryStream BmpMemory = new MemoryStream();
            GifPic.Start();
            //确保视觉残留
            GifPic.SetDelay(5);
            //-1:no repeat,0:always repeat
            GifPic.SetRepeat(0);
            for (int i = 0; i < 20; i++)
            {
                //创建一帧的图像
                CreateImageBmp(out ImageFrame);
                //生成随机线条
                DisposeImageBmp(ref ImageFrame);
                //输出绘图,将图像保存到指定的流
                ImageFrame.Save(BmpMemory, System.Drawing.Imaging.ImageFormat.Png);
                GifPic.AddFrame(Image.FromStream(BmpMemory));
                BmpMemory = new MemoryStream();
            }
            GifPic.OutPut(ref BmpMemory);
            HttpContext.Current.Response.ClearContent();
            //配置输出类型
            HttpContext.Current.Response.ContentType = "image/Gif";
            //输出内容
            HttpContext.Current.Response.BinaryWrite(BmpMemory.ToArray());
            BmpMemory.Close();
            BmpMemory.Dispose();
        }
        //输出验证码
        public void OutPutValidate(string ValidateCodeSession)
        {
            CreateValidate();
            CreateImageGif();
            //把生成的验证码输入到SESSION
            HttpContext.Current.Session[ValidateCodeSession] = ValidateCode;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值