C#实现的一款比较美观的验证码完整实例
本文实例讲述了C#实现的一款比较美观的验证码。分享给大家供大家参考,具体如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Drawing;
usingSystem.IO;
usingSystem.Drawing.Imaging;
publicpartialclassValidateCode:System.Web.UI.Page
{
privateintletterWidth=16;//单个字体的宽度范围
privateintletterHeight=22;//单个字体的高度范围
privateintletterCount=4;//验证码位数
privatechar[]chars="0123456789".ToCharArray();
privatestring[]fonts={"Arial","Georgia"};
///<summary>
///产生波形滤镜效果
///</summary>
privateconstdoublePI=3.1415926535897932384626433832795;
privateconstdoublePI2=6.283185307179586476925286766559;
protectedvoidPage_Load(objectsender,EventArgse)
{
//防止网页后退--禁止缓存
Response.Expires=0;
Response.Buffer=true;
Response.ExpiresAbsolute=DateTime.Now.AddSeconds(-1);
Response.AddHeader("pragma","no-cache");
Response.CacheControl="no-cache";
stringstr_ValidateCode=GetRandomNumberString(letterCount);
HttpCookieobjCookie=newHttpCookie("ValidateCode");
objCookie.Value=str_ValidateCode;
objCookie.Path="/";
objCookie.Expires=DateTime.Now.AddSeconds(1200);
Response.Cookies.Add(objCookie);
CreateImage(str_ValidateCode);
}
publicvoidCreateImage(stringcheckCode)
{
intint_ImageWidth=checkCode.Length*letterWidth;
RandomnewRandom=newRandom();
Bitmapimage=newBitmap(int_ImageWidth,letterHeight);
Graphicsg=Graphics.FromImage(image);
//生成随机生成器
Randomrandom=newRandom();
//白色背景
g.Clear(Color.White);
//画图片的背景噪音线
for(inti=0;i<10;i++)
{
intx1=random.Next(image.Width);
intx2=random.Next(image.Width);
inty1=random.Next(image.Height);
inty2=random.Next(image.Height);
g.DrawLine(newPen(Color.Silver),x1,y1,x2,y2);
}
//画图片的前景噪音点
for(inti=0;i<10;i++)
{
intx=random.Next(image.Width);
inty=random.Next(image.Height);
image.SetPixel(x,y,Color.FromArgb(random.Next()));
}
//随机字体和颜色的验证码字符
intfindex;
for(intint_index=0;int_index<checkCode.Length;int_index++)
{
findex=newRandom.Next(fonts.Length-1);
stringstr_char=checkCode.Substring(int_index,1);
BrushnewBrush=newSolidBrush(GetRandomColor());
PointthePos=newPoint(int_index*letterWidth+1+newRandom.Next(3),1+newRandom.Next(3));//5+1+a+s+p+x
g.DrawString(str_char,newFont(fonts[findex],12,FontStyle.Bold),newBrush,thePos);
}
//灰色边框
g.DrawRectangle(newPen(Color.LightGray,1),0,0,int_ImageWidth-1,(letterHeight-1));
//图片扭曲
//image=TwistImage(image,true,3,4);
//将生成的图片发回客户端
MemoryStreamms=newMemoryStream();
image.Save(ms,ImageFormat.Png);
Response.ClearContent();//需要输出图象信息要修改HTTP头
Response.ContentType="image/Png";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
///<summary>
///正弦曲线Wave扭曲图片
///</summary>
///<paramname="srcBmp">图片路径</param>
///<paramname="bXDir">如果扭曲则选择为True</param>
///<paramname="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
///<paramname="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
///<returns></returns>
publicSystem.Drawing.BitmapTwistImage(BitmapsrcBmp,boolbXDir,doubledMultValue,doubledPhase)
{
System.Drawing.BitmapdestBmp=newBitmap(srcBmp.Width,srcBmp.Height);
//将位图背景填充为白色
System.Drawing.Graphicsgraph=System.Drawing.Graphics.FromImage(destBmp);
graph.FillRectangle(newSolidBrush(System.Drawing.Color.White),0,0,destBmp.Width,destBmp.Height);
graph.Dispose();
doubledBaseAxisLen=bXDir?(double)destBmp.Height:(double)destBmp.Width;
for(inti=0;i<destBmp.Width;i++)
{
for(intj=0;j<destBmp.Height;j++)
{
doubledx=0;
dx=bXDir?(PI2*(double)j)/dBaseAxisLen:(PI2*(double)i)/dBaseAxisLen;
dx+=dPhase;
doubledy=Math.Sin(dx);
//取得当前点的颜色
intnOldX=0,nOldY=0;
nOldX=bXDir?i+(int)(dy*dMultValue):i;
nOldY=bXDir?j:j+(int)(dy*dMultValue);
System.Drawing.Colorcolor=srcBmp.GetPixel(i,j);
if(nOldX>=0&&nOldX<destBmp.Width&&nOldY>=0&&nOldY<destBmp.Height)
{
destBmp.SetPixel(nOldX,nOldY,color);
}
}
}
returndestBmp;
}
publicColorGetRandomColor()
{
RandomRandomNum_First=newRandom((int)DateTime.Now.Ticks);
System.Threading.Thread.Sleep(RandomNum_First.Next(50));
RandomRandomNum_Sencond=newRandom((int)DateTime.Now.Ticks);
intint_Red=RandomNum_First.Next(210);
intint_Green=RandomNum_Sencond.Next(180);
intint_Blue=(int_Red+int_Green>300)?0:400-int_Red-int_Green;
int_Blue=(int_Blue>255)?255:int_Blue;
returnColor.FromArgb(int_Red,int_Green,int_Blue);//5+1+a+s+p+x
}
//生成随机数字字符串
publicstringGetRandomNumberString(intint_NumberLength)
{
Randomrandom=newRandom();
stringvalidateCode=string.Empty;
for(inti=0;i<int_NumberLength;i++)
validateCode+=chars[random.Next(0,chars.Length)].ToString();
returnvalidateCode;
}
}
<imgalt="看不清,换一张"title="看不清,换一张"src="ValidateCode.aspx"style="cursor:pointer"onclick="this.src=this.src+'?r='+Math.random()"/>
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#中XML文件操作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》
希望本文所述对大家C#程序设计有所帮助。