Create validatecode. aspx
Its Background CS File Code As follows:
Pageload
Copy code The Code is as follows: Private void page_load (Object sender, system. eventargs E)
{
String checkcode = createrandomcode (4 );
Session ["checkcode"] = checkcode;
Createimage (checkcode );
}
Createrandomcode is a custom function, and the parameter represents the number of digits of the verification code.Copy codeThe Code is as follows: Private string createrandomcode (INT codecount)
{
String allchar = ", 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 (',');
String randomcode = "";
Int temp =-1; random Rand = new random ();
For (INT I = 0; I <codecount; I ++)
{
If (temp! =-1)
{
Rand = new random (I * temp * (INT) datetime. Now. ticks ));
}
Int T = Rand. Next (35 );
If (temp = T)
{
Return createrandomcode (codecount );
}
Temp = T;
Randomcode + = allchararray [T];
}
Return randomcode;
}
Createimage is also a custom function used to generate graphs. Copy code The Code is as follows: 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. imaging. imageformat. JPEG );
Response. clearcontent ();
Response. contenttype = "image/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 image. The for loop below is used to generate some random horizontal lines.
Add an control on the page where the verification code is needed, however, you need to point the imageurl to the page that generates the Verification Code copy Code the code is as follows: