1.新建一個頁面,ImageCode.aspx2.在Page_Load中添加如下代碼string tmp = RndNum(4); HttpCookie a = new HttpCookie("ImageV ", tmp); Respo...
1.新建一個頁面,ImageCode.aspx
2.在Page_Load中添加如下代碼
string tmp = RndNum(4);
HttpCookie a = new HttpCookie("ImageV ", tmp);
Response.Cookies.Add(a);
this.ValidateCode(tmp);
3.在該頁面中添加兩個方法
private void ValidateCode(string VNum)
{
Bitmap Img = null;
Graphics g = null;
MemoryStream ms = null;
int gheight = VNum.Length * 12;
Img = new Bitmap(gheight, 25);
g = Graphics.FromImage(Img);
//生成隨機生成器
Random random = new Random();
//背景顏色
g.Clear(Color.White);
for (int i = 0; i < 100; i++)
{
int x = random.Next(Img.Width);
int y = random.Next(Img.Height);
Img.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//文字字體
Font f = new Font("Arial Black ", 12);
//文字顏色
SolidBrush s = new SolidBrush(Color.Blue);
g.DrawString(VNum, f, s, 3, 3);
ms = new MemoryStream();
Img.Save(ms, ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType = "image/Jpeg ";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
Img.Dispose();
Response.End();
}
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(35);
if (temp != -1 && temp == t)
{
return RndNum(VcodeNum);
}
temp = t;
VNum += VcArray[t];
}
return VNum;
}
4.在需要顯示驗證碼的頁面添加一個圖片控制項
5.在該頁的前臺頁面添加如下代碼:
驗證碼:
<asp:TextBox ID="tbx_yzm" runat="server" Width="70px"></asp:TextBox>
<asp:ImageButton ID="ibtn_yzm" runat="server" />
<a href="javascript:changeCode()"style="text-decoration: underline; font-size:10px;">換一張</a>
<script type="text/javascript">
function changeCode()
{
document.getElementById('ibtn_yzm').src = document.getElementById('ibtn_yzm').src + '?';
}
</script>
6.在該頁的Page_Load事件中添加如下代碼:
ibtn_yzm.ImageUrl = "ImageCode.aspx";
7.驗證該驗證碼是否輸入正確的代碼:
string code = tbx_yzm.Text;
HttpCookie htco = Request.Cookies["ImageV"];
string scode = htco.Value.ToString();
if (code != scode)
{
Response.Write("<script>alert('驗證碼輸入不正確!')</script>");
}
8.效果