Using system;
Using system. Data;
Using system. configuration;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. Drawing; // Add reference
Public partial
Class
_ Default
: System. Web. UI. Page
{
Protected void
Page_load (Object sender,
Eventargs E)
{
Createcheckcodeimage (generatecheckcode ());
}
Private string
Generatecheckcode ()
{
Int number;
Char code;
String checkcode =
String. empty;
Random
Random = new random ();
For (int
I = 0; I <4; I ++)
{
Number = random. Next ();
If
(Number % 2 = 0)
Code = (char) ('0' + (char) (Number % 10 ));
Else
Code = (char) ('A' + (char) (Number % 26 ));
Checkcode + = code. tostring ();
}
Response. Cookies. Add (New
Httpcookie ("checkcode", checkcode ));
Return
Checkcode;
}
Private void
Createcheckcodeimage (string checkcode)
{
If (checkcode =
Null | checkcode. Trim () = string. Empty)
Return;
System. Drawing. Bitmap
Image = new system. Drawing. Bitmap (INT) math. Ceiling (checkcode. length * 12.5), 22 );
Graphics G =
Graphics. fromimage (image );
Try
{
// Generate a random Generator
Random random =
New random ();
// Clear the background color of the image
G. Clear (color. White );
// Draw the background noise line of the image
For (int
I = 0; I <2; 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. Black), X1, Y1, X2, Y2 );
}
Font
Font = new system. Drawing. Font ("Arial", 12, (system. Drawing. fontstyle. Bold ));
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 (checkcode, Font, brush, 2, 2 );
// Foreground noise of the image
For (int
I = 0; I <100; 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 image
G. drawrectangle (new pen (color. Silver), 0, 0, image. Width-1, image. Height-1 );
System. Io. memorystream
MS = new system. Io. memorystream ();
Image. Save (MS, system. Drawing. imaging. imageformat. GIF );
Response. clearcontent ();
Response. contenttype = "image/GIF ";
Response. binarywrite (Ms. toarray ());
}
Finally
{
G. Dispose ();
Image. Dispose ();
}
}
}