技术开发 频道

c# asp.net实现验证码


【IT168技术文档】

  建立ValidateImg.aspx文件,里面代码如下:
<%@ Page Language="c#" %> <%@ Import Namespace="System.Web" %> <%@ Import Namespace="System.Drawing" %> <%@ Import Namespace="System.Drawing.Imaging" %> <script runat="server" language="C#"> void Page_Load(Object sender, EventArgs e) { int charsNo = 4; int fontSize = 12; int bgWidth = 60; int bgHeight = 20; float x = (bgWidth - (charsNo * (fontSize + 0.5F))) / 2; // TODO: optimize float y = (bgHeight - (fontSize * 1.7F)) / 2; // TODO: optimize // Generate the text // //string genText = Globals.CreateTemporaryPassword(charsNo).ToUpper(); string genText = CreateTemporaryPassword(charsNo).ToUpper(); // Add the generate text to a session variable // Session.Add("ValidateNumber", genText); // Create the memory map // Bitmap raster; // Select an memory image from file of 290x80 px // in the current dir, NoSpamBgImgs folder named bg_X.jpg // Graphics graphicObj; string bgFilePath = Server.MapPath(@".\AntiSpamBgImgs\bg_" + new Random().Next(1) + ".jpg"); System.Drawing.Image imgObj = System.Drawing.Image.FromFile(bgFilePath); // Creating the raster image & graphic objects // raster = new Bitmap(imgObj, bgWidth, bgHeight); graphicObj = Graphics.FromImage(raster); // Creating an array for most readable yet cryptic fonts for OCR's // This is entirely up to developer's discretion // CAPTCHA recomandation // String[] crypticFonts = new String[13]; crypticFonts[0] = "Arial"; crypticFonts[1] = "Verdana"; crypticFonts[2] = "Comic Sans MS"; crypticFonts[3] = "Impact"; crypticFonts[4] = "Haettenschweiler"; crypticFonts[5] = "Lucida Sans Unicode"; crypticFonts[6] = "Garamond"; crypticFonts[7] = "Courier New"; crypticFonts[8] = "Book Antiqua"; crypticFonts[9] = "Arial Narrow"; crypticFonts[10] = "Fixedsys"; crypticFonts[11] = "宋体"; crypticFonts[12] = "仿体"; // Instantiate object of brush with black color // Random r = new Random(); SolidBrush brushes = new SolidBrush(Color.FromArgb(r.Next(150), r.Next(150), r.Next(150))); // Loop to write the characters on image with different fonts // CAPTCHA method // for (int a = 0; a < genText.Length; a++) { Font fontObj = new Font(crypticFonts[r.Next(crypticFonts.Length)], fontSize); graphicObj.DrawString(genText.Substring(a, 1), fontObj, brushes, x + (a * fontSize), y); } // Flush again // graphicObj.Flush(); // Setting the response header content MIME type // Response.ContentType = "image/gif"; // Saving the file to output stream to be displayed in browser // raster.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif); // Flushing to the Response // Response.Flush(); } public static String CreateTemporaryPassword(int length) { string str = ""; Random r = new Random(); for (int i = 0; i < length; i++) { str += r.Next(0, 9).ToString(); } return str; } </script>
0
相关文章