数字验证码

//ValidateCode.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Configuration;
namespace YanZhengMa
{
 /// <summary>
 /// ValidateCode 的摘要说明。
 /// </summary>
 public class ValidateCode : System.Web.UI.Page
 {
  private void Page_Load(object sender, System.EventArgs e)
  {     
   if(!IsPostBack)
   {
    //  从配置文件中读取到字符串长度
    int num=Convert.ToInt32(ConfigurationSettings.AppSettings["NUM"]);   
    string str_ValidateCode = GetRandomNumberString(num);
    //  用于验证的Session
    Session["ValidateCode"] = str_ValidateCode;
    CreateImage(str_ValidateCode);
   }
  }


  public string GetRandomNumberString(int int_NumberLength)
  {
   string str_Number = string.Empty;
   Random theRandomNumber = new Random();

   for (int int_index = 0; int_index < int_NumberLength; int_index++)
    str_Number += theRandomNumber.Next(10).ToString();

   return str_Number;
  }
  //生成随机颜色
  public Color GetRandomColor()
  {
   Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
   //  对于C#的随机数,没什么好说的
   System.Threading.Thread.Sleep(RandomNum_First.Next(50));
   Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);     

   //  为了在白色背景上显示,尽量生成深色
   int int_Red = RandomNum_First.Next(256);
   int int_Green = RandomNum_Sencond.Next(256);
   int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
   int_Blue = (int_Blue > 255) ? 255 : int_Blue;

   return Color.FromArgb(int_Red, int_Green, int_Blue);
  }

  public void CreateImage(string str_ValidateCode)
  {
   int int_ImageWidth = str_ValidateCode.Length * 13;
   Random newRandom = new Random();
   //  图高20px Bitmap 对象是用于处理由像素数据定义的图像的对象。
   Bitmap theBitmap = new Bitmap(int_ImageWidth, 20);
   //Graphics.FromImage创建新 Graphics 对象。
   Graphics theGraphics = Graphics.FromImage(theBitmap);
   //  白色背景
   theGraphics.Clear(Color.White);
   //  灰色边框   theGraphics.DrawRectangle画矩形   pen(画笔颜色,画笔宽度)
   //DrawRectangle(画笔,x,y,width,heigth)
   theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, 19);
   
   //  10pt的字体
   Font theFont = new Font("Arial", 10);

   for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
   {           
    //Substring(1,j) 从i开始取长度为j的字符
    string str_char = str_ValidateCode.Substring(int_index, 1);
    //调用随机返回的颜色方法
    Brush newBrush = new SolidBrush(GetRandomColor());
    //point(i,j)  i该点的水平位置,  j该点的垂直位置
    Point thePos = new Point(int_index * 13 + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
    theGraphics.DrawString(str_char, theFont, newBrush, thePos);
   }

   //  将生成的图片发回客户端
   MemoryStream ms = new MemoryStream();
   theBitmap.Save(ms, ImageFormat.Png);//以指定的格式保存到指定的流中

   Response.ClearContent(); //需要输出图象信息 要修改HTTP头
   Response.ContentType = "image/Png";
   Response.BinaryWrite(ms.ToArray());//将一个二进制字符串写入 HTTP 输出流
   theGraphics.Dispose();//释放由此 Graphics 对象使用的所有资源。
   theBitmap.Dispose();
   Response.End();
  }

  #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 void cmdSubmit_Click(object sender, System.EventArgs e)
  {
   if(txtNum.Text==Session["ValidateCode"].ToString())
   {
    Response.Write("ok");
   }
   else
   {
    Response.Write("wrong");
   }
  }

原文地址:https://www.cnblogs.com/88223100/p/1016215.html