非原创,借鉴别人改了一下的.
第一步,建一个面页ValidatePage.aspx
CodeBehind代码如下
.........
...........//这里是创建页面时默认的命名空间,下面三个是要自己添加的
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public partial class ValidatePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ValidateCode(); //生成验证码方法
}
//把随机数字与图形结合生成图片
private void ValidateCode() {
string validateCode = RndNum(4);// 设置随机数字为4个
Bitmap bitmap = new Bitmap(4*12,25); //长度,高度
Graphics g = Graphics.FromImage(bitmap);
g.Clear(Color.LightSteelBlue); //背景色
Font f = new Font("Arical Black",10); //字体
SolidBrush s = new SolidBrush(Color.RoyalBlue); //字颜色
g.DrawString(validateCode, f, s, 3, 3);
MemoryStream m = new MemoryStream();
bitmap.Save(m, ImageFormat.Jpeg); //图片格式
HttpCookie mycook = new HttpCookie("ValidateImage"); //用建值式保存进cookies
mycook["myKey"] = validateCode;
Response.Cookies.Add(mycook);
Response.ClearContent();
Response.ContentType = "images/Jpeg";
Response.BinaryWrite(m.ToArray());
g.Dispose(); //下面都是释放资源方法
bitmap.Dispose();
Response.End();
}
//生成随机数字方法
private string RndNum(int VcodeNum)
{
string vchar = "0,1,2,3,4,5,6,7,8,9,q,w,e,r,t,y,u,i,o,p" +
",a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
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;
}
}
第二步 建一个测试页面,html代码下写
<img src="ValidatePage.aspx" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="test" Width="209px"
οnclick="Button1_Click" /><br />
第三步 双击button进入CodeBehind下
if (Request.Cookies["ValidateImage"]!= null) { string valid = Request.Cookies["ValidateImage"]["myKey"].ToString(); if (TextBox1.Text.ToString() == valid) { Response.Write("Great. the validate is success."); //go to do that you wamna. } else { Response.Write("Not same!"); } } else { Response.Write("That is bad luck,your IE is not allow to using 'Cookies'."); }