最近看书学习了如何随机生成验证码,感觉不错,把源代码分享给大家!希望大家互相学习!!!!(1)创建一个项目,添加一个CreateImage.aspx文件,代码如下:public partial class CreateImage : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { createImageM(createValidate(5)); } private string createValidate(int count) { string AllChar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,O,P,Q,R,I,S,T,U,V,W,X,Y,Z"; string[] allCharArray = AllChar.Split(','); //初始化一个存储随机数的变量 string randomCode = ""; int temp = -1; Random rand = new Random(); for (int i = 0; i < count; i++) { if (temp != -1) { rand = new Random(i*temp*((int)DateTime.Now.Ticks)); } int t = rand.Next(35); if (temp == t) { return createValidate(count); } temp = t; randomCode += allCharArray[i]; } Session["valid"] = randomCode; return randomCode; } private void createImageM(string validateCode) { int iwidth = (int)(validateCode.Length * 19); Bitmap image = new Bitmap(iwidth,34); Graphics graphics = Graphics.FromImage(image); Font font = new Font("Arial",18,FontStyle.Bold|FontStyle.Italic); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0,0,image.Width,image.Height),Color.DarkOrchid,Color.Blue,1.5f,true); graphics.Clear(System.Drawing.Color.White); graphics.DrawString(validateCode,font,brush,3,3); Random ran = new Random(); for (int i = 0; i < 500; i++) { int x = ran.Next(image.Width); int y = ran.Next(image.Height); image.SetPixel(x,y,Color.FromArgb(ran.Next())); } graphics.DrawRectangle(new Pen(Color.DarkBlue),0,0,image.Width-1,image.Height-1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg); Response.ClearContent(); Response.ContentType = "image/Jpeg"; Response.BinaryWrite(ms.ToArray()); graphics.Dispose(); image.Dispose(); }}(2)再创建一个aspx文件来调用随机验证码。此处是div标签内的代码:<div> 验证码: <asp:Image ID="Image1" runat="server" Height="31px" Width="92px" ImageUrl="~/CreateImage.aspx"/> <br /> 输入验证码:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /> <asp:Button ID="Button1" runat="server" Text="验证" /> </div>在cs文件中:protected void Button1_Click(object sender, EventArgs e) { if (TextBox1.Text.ToString() == Session["valid"].ToString()) { Response.Write("<script>alert('验证通过!')</script>"); } else { Response.Write("<script>alert('验证码输入错误!')</script>"); } }
本文转自 王祖康 51CTO博客,原文链接:http://blog.51cto.com/wzk89/356915,如需转载请自行联系原作者