1.ASP.NET验证码制作
ASP.NET验证码制作
百度搜索
asp.net 验证码就出来了
image.aspx
加载事件里面:
using System.Xml.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
/// <summary>
/// 加载事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender,验源码e验空降直播源码 EventArgs e)
{
string tmp = RndNum(6);
Session["validation"] = tmp;
HttpCookie a = new HttpCookie("ImageV ", tmp);
Response.Cookies.Add(a);
this.ValidateCode(tmp);
}
/// <summary>
/// 生成验证
/// </summary>
/// <param name="VNum"></param>
private void ValidateCode(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * .5)), );
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空背景色
g.Clear(Color.White);
//画的背景噪音线
for (int i = 0; i < 2; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Arial", , (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//画的前景噪音点
for (int i = 0; i < ; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "image/Gif";
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
private string RndNum(int VcodeNum)
{
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 ";
string[] VcArray=Vchar.Split(new Char [] { ','});
string VNum= " ";
int temp=-1;
Random rand=new Random();
for(int i=1;i <VcodeNum+1;i++)
{
if(temp!=-1)
{
rand=new Random(i*temp*unchecked((int)DateTime.Now.Ticks));
}
int t=rand.Next();
if(temp!=-1&&temp==t)
{
return RndNum(VcodeNum);
}
temp=t;
VNum+=VcArray[t];
}
return VNum;
}
页面调用2方法:
string yanzhem =Convert.ToString(Session["validation"]);
加载事件里面: chkImageButton.ImageUrl = "image.aspx ";
1.
<img src="image.aspx" alt="验证码" height="" width="" onclick="this.src=this.src+'?' />
2.
<asp:ImageButton runat="server" ID="ImageUrl="image.aspx" onclick="this.src=this.src+'?' />