ASP.NET (C #) Implementation Verification Code Function (Reposted)

xiaoxiao2021-03-06  38

Create a new page of the page ValidateCode.aspx for creating a verification code picture, its background CS file code is as follows: PageLoad

Private

Void

Page_load

Object

Sender, System.EventArgs E)

{String Checkcode = CreaterandMcode (4); session ["Checkcode"] = Checkcode; Creckcode (checkcode);

Where CreaterandMcode is a custom function, the parameter represents the number of verification code bits.

Private

String

CreaterAndomcode

int

CodeCount

{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, Z "; string [] allchararray = allchar.split (','); string randomcode =" "; int temp = 1; random rand = new random (); for (int i = 0; i

CREATEIMAGE is also a custom function for generating diagrams

Private

Void

CREATEIMAGE

String

Checkcode

{Int iwidth = (int) (checkCode.Length * 11.5); System.Drawing.Bitmap image = new System.Drawing.Bitmap (iwidth, 20); Graphics g = Graphics.FromImage (image); Font f = new System. Drawing.font ("Arial", 10, System.drawing.FontStyle.bold; brush b = new system.drawing.solidbrush (color.White); //g.FillRectangle (New System.drawing.Solidbrush (Color.Blue ), 0, 0, image.width, image.Height); g.clear (color.blue); g.drawstring (Checkcode, F, B, 3, 3); Pen Blackpen = New Pen (Color.Black, 0 ); Random rand = new random (); for (int i = 0; i <5; i ) {int y = rand.next (image.height); g.drawline (Blackpen, 0, Y, Image.Width, y);} system.io.MemoryStream ms = new system.io.MemoryStream (); image.save (ms, system.drawing.Image.imageformat.jpeg); response.clearcontent (); response.contenttype = "iMA GE / JPEG "; response.binaryWrite (ms.toarray ()); g.dispose (); image.dispose ();} // g.fillRectangle (new system.drawing.solidbrush (color.blue), 0,0 Image.width, image.Height; g.clear (color.blue); Both methods can change the background color of the generated picture below the FOR cycle to generate some random horizontal lines and then write on the page that requires the verification code Enter the code: