Effect:
Default.aspx
<table> <tr> <td class= "Style1" > (Verification Code test) </td> <td> <asp:label id= "Label1" runat= "Server" ></asp:Label> <asp:image id= "Image1" runat= "Server" height= "22px" imageurl= "~/ Validnums.aspx "width=" 58px "/> <asp:image id=" Image2 "runat=" Server "height=" 22px "imageurl=" ~/ Getvalid.aspx "width=" 58px "/></td> </tr> <tr> <td class=" Style1 "> </td> <td > <asp:button id= "Button1" runat= "server" text= "login" onclick= "Btnok_click"/> <asp:button id= " Button2 "runat=" Server "text=" Cancel/> </td> </tr> </table>
Using System; Using System.Collections.Generic; Using System.Linq; Using System.Web; Using System.Web.UI; Using System.Web.UI.WebControls; Public partial class _default:system.web.ui.page {protected void Page_Load (object sender, EventArgs e) {if (! Page.IsPostBack) {String getnums = Getvali (); Label1.Text = Getnums; }}///<summary>///Generate 4 digits////</summary>//<returns> Returns the generated random number </returns> public string Getvali () {String Strsvali = "0,1,2,3,4,5,6,7,8,9"; string[] Valiarray = Strsvali. Split (', '); String returnnum = ""; int nums =-1; Random Vrand = new Random (); for (int n = 1; n < 5; n++) {if (nums! =-1) {Vrand = new Random (n * nums * Unchecked ((int) DateTime.Now.Ticks));} in T t = Vrand. Next (10); Nums = t; Returnnum + = valiarray[t]; } session["Valid"] = Returnnum; return returnnum; } protected void Btnok_click (object sender, EventArgs e) {if (session["Valid"]. ToString () = = TextBox3.Text) {Clientscript.registerstartupscript (this. GetType (), "SS", "< Script>alert (' You have successfully verified by login! ') </script> "); } else {Clientscript.registerstartupscript (this. GetType (), "SS", "<script>alert (' you entered a wrong CAPTCHA! ') </script> "); } } }
Getvalid.aspx
(You can assign the page as a source directly to ImageUrl)
The foreground is empty and the background code is as follows:
Using System; Using System.Collections; Using System.Configuration; Using System.Data; Using System.Linq; Using System.Web; Using System.Web.Security; Using System.Web.UI; Using System.Web.UI.HtmlControls; Using System.Web.UI.WebControls; Using System.Web.UI.WebControls.WebParts; Using System.Xml.Linq; Using System.Text; Using System.Drawing; Public partial class GetValid:System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {if (! IsPostBack) {String validatenum = Getvalids ();//Genetic 4-bit random string createimage (validatenum);//plot The resulting random string into a picture session[" Validnums "] = Validatenum; Save Verification Code}} public static string Getvalids () {//Get GB2312 Encoding page (table) Encoding GB = encoding.getencoding ("gb2312");//Call function generates 4 random Chinese Chinese character coding object[] bytes = Createregioncode (4); Decodes the Chinese character string s = String.Empty According to the Chinese character coding byte array; foreach (Object byt in bytes) {string str1 = GB. GetString ((byte[]) Convert.changetype (Byt, typeof (byte[))); s = s + str1; }//output of the console return s; } public static object[] Createregioncode (int sTrlength) {//define a string array to store Chinese character coding's constituent elements string[] rBase = new String[16] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a" , "B", "C", "D", "E", "F"}; Random rnd = new Random (); Define an object array to object[] bytes = new Object[strlength]; /* Produces a hexadecimal byte array with two elements at a time per loop, and puts it into the bject array each character has four location codes, the 1th bit and the location code 2nd bits as the byte array the first element location code 3rd bit and Location code 4th bit as byte array the second element */for (int i = 0; i < strlength; i++) {//Location code 1th bit int r1 = rnd. Next (11, 14); String str_r1 = Rbase[r1]. Trim (); Location Code 2nd rnd = New Random (R1 * Unchecked ((int) DateTime.Now.Ticks) + i); Replace the seed of the random number generator to avoid producing duplicate values int R2; if (r1 = =) {r2 = rnd. Next (0, 8); } else {r2 = rnd. Next (0, 16); } string str_r2 = Rbase[r2]. Trim (); Location Code 3rd rnd = new Random (R2 * Unchecked ((int) DateTime.Now.Ticks) + i); int r3 = rnd. Next (10, 16); String str_r3 = Rbase[r3]. Trim (); Location Code 4th rnd = New Random (R3 * Unchecked ((int) DateTime.Now.Ticks) + i); int R4; if (R3 = =) {R4 = rnd. Next (1, 16); } else if (r3 = =) {R4 = rnd. Next (0, 15); } else {r4 = rnd. Next (0, 16); } string STR_R4= Rbase[r4]. Trim (); Defines a two-byte variable storage generated by the random Chinese character location code byte byte1 = convert.tobyte (str_r1 + str_r2, 16); byte Byte2 = convert.tobyte (Str_r3 + STR_R4, 16); Store two byte variables in a byte array byte[] Str_r = new byte[] {byte1, byte2}; The resulting byte array of a Chinese character is placed in the object array bytes. SetValue (Str_r, i); } return bytes; }//Generate picture private void CreateImage (string validatenum) {if (Validatenum = = NULL | | Validatenum.trim () = = String.Empty) ret Urn Generate Bitmap images System.Drawing.Bitmap image = new System.Drawing.Bitmap (validatenum.length * 12 + 10, 22); Graphics g = graphics.fromimage (image); try {//Generate random generator randomly random = new random ();//Empty picture background color g.clear (color.white);//Picture background noise line for (int i = 0; i <; i++) {int x1 = random. Next (image. Width); int x2 = random. Next (image. Width); int y1 = random. Next (image. Height); int y2 = random. Next (image. Height); G.drawline (New Pen (color.coral), x1, y1, x2, y2); } Font font = new System.Drawing.Font ("Arial", 8); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientbrush (New Rectangle (0, 0, image. Width, image. Height), Color.Blue, color.darkred, 1.2f, true); g.DrawString (validatenum, Font, brush, 2, 2); Picture the foreground noise point for (int i = 0; i < i++) {int x = random. Next (image. Width); int y = random. Next (image. Height); Image. SetPixel (x, Y, Color.FromArgb (random. Next ())); }//Draw the border line of the picture G.drawrectangle (new Pen (Color.silver), 0, 0, image. Width-1, image. HEIGHT-1); System.IO.MemoryStream ms = new System.IO.MemoryStream (); Saves the image to the specified stream image. Save (MS, SYSTEM.DRAWING.IMAGING.IMAGEFORMAT.GIF); Response.clearcontent (); Response.ContentType = "Image/gif"; Response.BinaryWrite (Ms. ToArray ()); } finally {g.dispose (); image. Dispose (); } } }
Validnums.aspx
(You can assign the page as a source directly to ImageUrl)
The foreground is empty and the background code is as follows:
Using System; Using System.Collections; Using System.Configuration; Using System.Data; Using System.Linq; Using System.Web; Using System.Web.Security; Using System.Web.UI; Using System.Web.UI.HtmlControls; Using System.Web.UI.WebControls; Using System.Web.UI.WebControls.WebParts; Using System.Xml.Linq; Using System.Drawing; Public partial class ValidNums:System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {if (! IsPostBack) {String validatenum = Createrandomnum (4);//Genetic 4-bit random string createimage (validatenum);//plot The resulting random string into a picture session[" Validnums "] = Validatenum; Save Verification Code}}/Generate random string Createrandomnum private string (int numcount) {string Allchar = "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,w,x,y,z "; string[] Allchararray = Allchar.split (', ');//split into an array of string randomnum = ""; int temp = -1;//records The value of the last random number, trying to avoid generating several identical random numbers for the randomness rand = new Random (); for (int i = 0; i < Numcount; i++) {if (temp! =-1) {rand = new Random (i * temp * ((int) DateTime.Now.Ticks)); } int t = rand. Next (35); if (temp = = t) {return createrandomnum (numcount);} temp = t; Randomnum + = allchararray[t]; } return randomnum; }//Generate picture private void CreateImage (string validatenum) {if (Validatenum = = NULL | | Validatenum.trim () = = String.Empty) ret Urn Generate Bitmap images System.Drawing.Bitmap image = new System.Drawing.Bitmap (validatenum.length * 12 + 10, 22); Graphics g = graphics.fromimage (image); try {//Generate random generator randomly random = new random ();//Empty picture background color g.clear (color.white);//Picture background noise line for (int i = 0; i <; i++) {int x1 = random. Next (image. Width); int x2 = random. Next (image. Width); int y1 = random. Next (image. Height); int y2 = random. Next (image. Height); G.drawline (New Pen (color.coral), x1, y1, x2, y2); } Font font = new System.Drawing.Font ("Arial", and (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush (New Rectangle (0, 0, image.) Width, image. Height), ColOr. Blue, color.darkred, 1.2f, true); g.DrawString (validatenum, Font, brush, 2, 2); Picture the foreground noise point for (int i = 0; i < i++) {int x = random. Next (image. Width); int y = random. Next (image. Height); Image. SetPixel (x, Y, Color.FromArgb (random. Next ())); }//Draw the border line of the picture G.drawrectangle (new Pen (Color.silver), 0, 0, image. Width-1, image. HEIGHT-1); System.IO.MemoryStream ms = new System.IO.MemoryStream (); Saves the image to the specified stream image. Save (MS, SYSTEM.DRAWING.IMAGING.IMAGEFORMAT.GIF); Response.clearcontent (); Response.ContentType = "Image/gif"; Response.BinaryWrite (Ms. ToArray ()); } finally {g.dispose (); image. Dispose (); } } }
The above is the entire code for 3 types of verification codes. The
can also use ASHX to request a verification code, this example only uses session stored value processing.