字符图象验证 示例+代码

例子请看:http://cnnet.europe.webmatrixhosting.net/csharp/isv/isv.aspx
代码下载:http://kyokyo66.vicp.net/williamxu/download/isv.rar 取消
或者
http://cnnet.europe.webmatrixhosting.net/csharp/isv/isv.cs 取消
http://cnnet.europe.webmatrixhosting.net/csharp/isv/img.cs 取消

发现这两个链接有问题,那我直接贴代码吧 (2004-5-13)
--------------------------------------------------------------------------------
-------------------------  Isv.aspx.cs Part Code   -----------------------------
--------------------------------------------------------------------------------
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.Reflection;

namespace isv
{
 /// <summary>
 /// ****************************************************************
 /// Made By WilliamXu
 /// 2003 12 30
 /// Mail:xuxy@trimps.ac.cn
 /// MSN:matataxu@hotmail.com
 /// ****************************************************************
 /// </summary>
 public class isv : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Label Label2;
  protected System.Web.UI.WebControls.Label Label4;
  protected System.Web.UI.WebControls.DropDownList ddlfont;
  protected System.Web.UI.WebControls.DropDownList ddlcount;
  protected System.Web.UI.WebControls.Label Label5;
  protected System.Web.UI.WebControls.Image Image1;
  protected System.Web.UI.WebControls.Button btn;
  protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
  protected System.Web.UI.WebControls.TextBox tb;
  protected System.Web.UI.WebControls.CheckBox cb;
  protected System.Web.UI.HtmlControls.HtmlSelect Select1;
  protected System.Web.UI.WebControls.Label Label3;
  protected System.Web.UI.WebControls.HyperLink HyperLink1;
  protected System.Web.UI.WebControls.Button btnReFlash;
  protected System.Web.UI.WebControls.Label lbResult;
  protected System.Web.UI.WebControls.Label Label1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面

   if(!IsPostBack)
   {
    //绑定字体
    BoundFont();

                //绑定颜色
    GetColor();

    //获取数据
    Session["RandomString"]=this.RndNum(int.Parse(this.ddlcount.SelectedItem.Value));
    Session["RandomColor"]="Blue";
    Session["RandomFont"]=this.cb.Checked?"RandomFont":this.ddlfont.SelectedValue;
   }

   //设置背景色
   GetBackGroudCol();
 
  }

  //获取字体
  private void BoundFont()
  {
   string sep=",";
   char[] sepch=sep.ToCharArray();
   string Vchar ="Arial,Arial Narrow,Basemic,Basemic Symbol,Basemic Times,Book Antiqua,Bookman Old Style,Comic Sans MS,Courier New,Microsoft Sans Serif,MS Reference Sans Serif,Verdana";
   string[] Varray= Vchar.Split(sepch,Vchar.Length);
   for(int i=0;i<Varray.Length;i++)
   {
    ddlfont.Items.Add(Varray[i]);
   }
  }

  //获取颜色
  private void GetColor()
  {
   //方法1
//   foreach(FieldInfo col in typeof(KnownColor).GetFields() )
//   {
//    if (col.FieldType == typeof(KnownColor) )
//    {
//     this.ddlbcolor.Items.Add(new ListItem(col.Name ,col.Name));
//    }
//   } 
//
//   
//   for (int i= 0 ;i < ddlbcolor.Items.Count;i++)
//   {
//    ddlbcolor.Items[i].Attributes.Add("style", "background-color:" + ddlbcolor.Items[i].Text);
//   }

   //方法2
   foreach(Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues())
   {
    ListItem li = new ListItem();
    li.Text = TypeDescriptor.GetConverter(c).ConvertToString(c);
    this.Select1.Items.Add(li);
   }
  
  }

  //获取颜色
  private void GetBackGroudCol()
  {
   for (int i= 0 ;i < this.Select1.Items.Count;i++)
   {
    this.Select1.Items[i].Attributes.Add("style", "background-color:" + this.Select1.Items[i].Value );
   }
  }

 

  //获取随机字符串
  private string RndNum(int strLen)
  {
   string sep=",";
   char[] sepch=sep.ToCharArray();
   string Vchar ="0,1,2,3,4,5,6,7,8,9,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,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";
   string[] Varray= Vchar.Split(sepch,Vchar.Length);


   string VNum=string.Empty;
   Random rnd=new Random();
   for(int i=0;i<strLen;i++)
   {    
    VNum += Varray[(int)(rnd.NextDouble()*(Varray.Length-1))]; //数组一般从0开始读取,所以这里为35*Rnd
   }
   return VNum;
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.ddlcount.SelectedIndexChanged += new System.EventHandler(this.ddlcount_SelectedIndexChanged);
   this.cb.CheckedChanged += new System.EventHandler(this.cb_CheckedChanged);
   this.btn.Click += new System.EventHandler(this.btn_Click);
   this.Select1.ServerChange += new System.EventHandler(this.Select1_ServerChange);
   this.btnReFlash.Click += new System.EventHandler(this.btnReFlash_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void btn_Click(object sender, System.EventArgs e)
  {
            //(tb.Text==(string)Session["RandomString"])?this.lbResult.Text=@"验证通过!":this.lbResult.Text=@"验证失败!";
   if(tb.Text==(string)Session["RandomString"])
   {this.lbResult.Text=@"Success!";}
   else
   {this.lbResult.Text=@"Fail!";}

   //验证后清除输入
   //this.tb.Text=string.Empty;

   //获取随机字符串
   Session["RandomString"]=this.RndNum(int.Parse(this.ddlcount.SelectedItem.Value));
  }

  //获取随机字符串
  private void ddlcount_SelectedIndexChanged(object sender, System.EventArgs e)
  {
   Session["RandomString"]=this.RndNum(int.Parse(this.ddlcount.SelectedItem.Value));
  }


  //获取字体
  private void cb_CheckedChanged(object sender, System.EventArgs e)
  {
   Session["RandomColor"]=this.Select1.Value; 
   Session["RandomFont"]=this.cb.Checked?"RandomFont":this.ddlfont.SelectedValue;
  }


  //获取前景色
  private void Select1_ServerChange(object sender, System.EventArgs e)
  {
            Session["RandomColor"]=this.Select1.Value;  
  }

  private void btnReFlash_Click(object sender, System.EventArgs e)
  {
   Session["RandomString"]=this.RndNum(int.Parse(this.ddlcount.SelectedItem.Value));
   Session["RandomColor"]=this.Select1.Value; 
  }

 }
}


--------------------------------------------------------------------------------
-------------------------  Img.aspx.cs Part Code   -----------------------------
--------------------------------------------------------------------------------

  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;

namespace isv
{
 /// <summary>
 /// ****************************************************************
 /// Made By WilliamXu
 /// 2003 12 30
 /// Mail:xuxy@trimps.ac.cn
 /// MSN:matataxu@hotmail.com
 /// ****************************************************************
 /// </summary>
 public class img : System.Web.UI.Page
 {
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   DrawString((string)Session["RandomString"],(string)Session["RandomFont"],(string)Session["RandomColor"]);
  }


  private void DrawString(string str,string font,string col)
  {
   //获取字体
   string sep=",";
   char[] sepch=sep.ToCharArray();
   string Vchar ="Arial,Arial Narrow,Book Antiqua,Bookman Old Style,Comic Sans MS,Courier New,Microsoft Sans Serif,MS Reference Sans Serif,Verdana";
   string[] Varray= Vchar.Split(sepch,Vchar.Length);

   //画图
   System.Drawing.Bitmap  img;
   System.Drawing.Graphics g;
   System.IO.MemoryStream ms;
   int gheight=(int)str.Length *10;  //gheight为图片宽度
   img=new Bitmap(gheight,20);    //创建图像
   g=Graphics.FromImage(img);

   if(font=="RandomFont")
   {
    Random rnd=new Random();
    for(int i=0;i<str.Length;i++)   //画图
    {
     g.DrawString(str.Substring(i,1),
      new Font((string)Varray[(int)(rnd.NextDouble()*Varray.Length)],10),
      new SolidBrush(Color.FromName(col)),
      new PointF(i*8,4));
    }
   }
   else
   {
    g.DrawString(str,
     new Font(font,10),
     new SolidBrush(Color.Blue),
     new PointF(2,4));
   }

   ms = new System.IO.MemoryStream();
   img.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
   Response.ClearContent();
   Response.ContentType="image/png";
   Response.BinaryWrite(ms.ToArray());
   Response.End();
   //img.Save(Server.MapPath(@"../isv/gg.png"),System.Drawing.Imaging.ImageFormat.Png);

   g.Dispose();
   img.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
 }
}


功能:
1、可以选择字符串长度
2、可以选择图象中字符颜色
3、产生随机字体或者指定字体的验证图象



Made By WilliamXu? 2003.12.30

posted on 2004-01-30 15:42  WilliamXu.Net  阅读(1962)  评论(5编辑  收藏  举报

导航