String *I am String* (自由大过天) 路漫漫其修远兮,吾以上下而求索

(道,可道,非常道)-----天之道,利而不害。圣人之道,为而不争。信言不美,美言不信。善者不辩,辩者不善。知者不博,博者不知。

导航

浅谈验证码

Posted on 2004-11-30 23:19  goodbaby  阅读(501)  评论(0)    收藏  举报
参考了一些blog和一些新闻组,我选取了一种简单可行的方案,就是用Session来保存验证码。我进行了简单的实现。
下面是一些代码片段:

private void btnTest_Click(object sender, System.EventArgs e)
  {
   if(int.Parse(txtCode.Text)==(int)Session["Code"])
      Response.Redirect("AnotherPage.aspx");//用于测试页
   lblStatus.Text="sorry Authentication is not match";
   BuildRandom();
  }

用于生成随机数。
  private void BuildRandom()
  {
   Random random=new Random();
   int AuthenticationCode=random.Next(1000,9999);//产生四位随机数
   Session["Code"]=AuthenticationCode;//save in server for authenticate
   Code.Src="Code.aspx";
  }
最后是一个绘图函数:

 Response.ContentType="image/gif";
   string text=((int)Session["Code"]).ToString();
            Bitmap CodePic=new Bitmap(50,30);
   Graphics oGraphics=Graphics.FromImage(CodePic);
   DrawText(oGraphics,0,0,50,30,text);
   Response.ClearContent();
   CodePic.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Gif);
            oGraphics.Dispose();
   CodePic.Dispose();
  }

  private void DrawText(Graphics oGraphics,int iTop,int iLeft,int iWidth,int iHeight,string sText)
  {
   SolidBrush oBrushForBack=new SolidBrush(Color.DeepPink);
   oGraphics.FillRectangle(oBrushForBack,0,0,iWidth,iHeight);//将位图刷白
   FontStyle eFontStyle=FontStyle.Regular;//字体样式
   int iFontSize=8;
   string sColor="Black";
   StringAlignment eAlign=StringAlignment.Near;
   StringFormatFlags eFlag=StringFormatFlags.DirectionVertical;
   Rectangle oRect=new Rectangle(iTop,iLeft,iWidth,iHeight);
   Font oFont=new Font("Arial",iFontSize,eFontStyle);
   StringFormat oFormat=new StringFormat();//字符串格式
   oFormat.Alignment=eAlign;//设置字符串格式
   oFormat.LineAlignment=StringAlignment.Center;//设置字符串格式
   SolidBrush oBrush=new SolidBrush(Color.FromName(sColor));
   oGraphics.DrawString(sText,oFont,oBrush,oRect,oFormat);
   oBrush.Dispose();
   oBrushForBack.Dispose();
  }



很简单。在浏览器里执行后,第一次很慢,但后来载入图片就很快了。