如果想进行登陆的时候验证。只要判断用户输入的数据是否和Session[“Validate”]相等就行了 using System; using System.Drawing; public partial class 生成随机图片 : System.Web.UI.Page { //生成随机图片背景 protected void CreateImageM(string validateCode) { //图像的宽度,与验证码的长度成一定比例 int iwidth = (int)(validateCode.Length * 11.5); //创建一个长20,宽iwidth的图像对象 System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth,20); //创建一个新绘图对象 Graphics g = Graphics.FromImage(image); //绘图用的字体和字号 Font f = new System.Drawing.Font("Arial",10,System.Drawing.FontStyle.Bold); //绘图用的刷子的大小 Brush b = new System.Drawing.SolidBrush(Color.White); //清除背景色,并且以深橄榄色填充 g.Clear(Color.DarkOliveGreen); //格式化刷子的属性,用指定的刷子、颜色等在指定的范围内画图 g.DrawString(validateCode,f,b,3,3); //创建铅笔对象 Pen blackPen = new Pen(Color.Black,0); //创建随机对象 Random rand = new Random(); //随机画线 for (int i = 0; i < 5; i++) { int y = rand.Next(image.Height); //用指定的铅笔画线,粗细由参数决定 g.DrawLine(blackPen,0,y,image.Width,y); } //输出绘图 System.IO.MemoryStream ms = new System.IO.MemoryStream(); //将图像保存到指定的流 image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg); Response.ClearContent(); //配置输出类型 Response.ContentType = "Image/Jpeg"; //输入内容 Response.BinaryWrite(ms.ToArray()); //清空不需要的资源 g.Dispose(); image.Dispose(); } //生成随机字符的方法 protected string CreateValidate(int count) { 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,V,W,X,Y,Z"; //将验证码中所有的字符保存在一个字符串数组中 string[] allchararray = allchar.Split(','); //初始化一个随机数 string randomcode = ""; int temp = -1; //生成一个随机对象 Random rand = new Random(); //根据验证码的位数循环 for (int i = 0; i < count; i++) { //主要是防止生成相同的验证码 if (temp != -1) { //加入时间的刻度 rand = new Random(i*temp*((int)DateTime.Now.Ticks)); } int t = rand.Next(35); if (temp == t) { //相等的话重新生成 return CreateValidate(count); } temp = t; randomcode += allchararray[t]; } //在session中保存随机验证码 Session["Valid"] = randomcode; //返回生成的随机字符 return randomcode; } protected void Page_Load(object sender, EventArgs e) { CreateImageM(CreateValidate(8)); } }