標籤:
登陸時驗證碼的製作(asp.net)
1、顯示樣式:
2.建立一個頁,Default2.aspx
3.在Page_load事件拷入如下代碼
stringtmp = RndNum(4);
HttpCookiea =newHttpCookie("ImageV ", tmp);
Response.Cookies.Add(a);
this.ValidateCode(tmp);
4、在該頁添加兩個方法:
privatevoidValidateCode(stringVNum)
{
BitmapImg =null;
Graphicsg =null;
MemoryStreamms =null;
intgheight = VNum.Length * 12;
Img =newBitmap(gheight, 25);
g =Graphics.FromImage(Img);
//生¦¨²成¨¦隨?機¨²生¦¨²成¨¦器¡Â
Randomrandom =newRandom();
//背À3景¡ã顏?色¦?
g.Clear(Color.Orange);
//for (int i = 0; i < 25; i++)
//{
// int x1 = random.Next(Img.Width);
// int x2 = random.Next(Img.Width);
// int y1 = random.Next(Img.Height);
// int y2 = random.Next(Img.Height);
// g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
//}
//畫-圖ª?片?的Ì?前¡ã景¡ã噪?音°?點Ì?
for(inti = 0; i < 100; i++)
{
intx = random.Next(Img.Width);
inty = random.Next(Img.Height);
Img.SetPixel(x, y,Color.FromArgb(random.Next()));
}
//文?字Á?字Á?體¬?
Fontf =newFont("Arial Black ", 12);
// 文?字Á?顏?色¦?
SolidBrushs =newSolidBrush(Color.White);
g.DrawString(VNum, f, s, 3, 3);
ms =newMemoryStream();
Img.Save(ms, ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType ="image/Jpeg ";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
Img.Dispose();
Response.End();
}
privatestringRndNum(intVcodeNum)
{
stringVchar ="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(newChar[] {‘,‘});
stringVNum =" ";
inttemp = -1;
Randomrand =newRandom();
for(inti = 1; i < VcodeNum + 1; i++)
{
if(temp != -1)
{
rand =newRandom(i * temp *unchecked((int)DateTime.Now.Ticks));
}
intt = rand.Next(35);
if(temp != -1 && temp == t)
{
returnRndNum(VcodeNum);
}
temp = t;
VNum += VcArray[t];
}
returnVNum;
}
5、在建立一個頁面用來顯示驗證碼:
則在該頁面添加一個圖片控制項
6、在該頁的Page_load事件中添加
ImageButton1.ImageUrl ="Default2.aspx";
7.前台頁面添加:
<asp:ImageButtonID="ImageButton1"runat="server"Width="100"Height="30"/>
看不清?<ahref="javascript:changeCode()"style="text-decoration: underline;">換一張</a>
<scripttype="text/javascript">
functionchangeCode() {
document.getElementById(‘ImageButton1‘).src = document.getElementById(‘ImageButton1‘).src +‘?‘;
}
</script>
這樣就完成啦!
登陸時驗證碼的製作(asp.net)