First, create a verification code page validatecode. aspx
Defining variables is conducive to later modification.
CopyCode The Code is as follows: Private int codelen = 4; // verification code length
Private int fineness = 85; // image definition
Private int imgwidth = 48; // Image Width
Private int imgheight = 24; // Image Height
Private string fontfamily = "Times New Roman"; // font name
Private int fontsize = 14; // font size
Private int fontstyle = 0; // Font Style
Private int posx = 0; // draw the starting coordinate X
Private int posy = 0; // draw coordinate Y
Private string createvalidatecode () // generate the verification code
{
String validatecode = "";
Random random = new random (); // random number object
For (INT I = 0; I <codelen; I ++) // generate each value in a loop
{
Int n = random. Next (10); // number
Validatecode + = n. tostring ();
}
Session ["vcode"] = validatecode; // Save the verification code
Return validatecode; // return the verification code
}
Private void disturbbitmap (Bitmap bitmap) // image background
{
Random random = new random (); // generate a random number
For (INT I = 0; I <bitmap. width; I ++) // generate one by one pixel through nested loops
{
For (Int J = 0; j <bitmap. height; j ++)
{
If (random. Next (90) <= This. fineness)
Bitmap. setpixel (I, j, color. lightgray );
}
}
}
Private void drewvalidatecode (Bitmap bitmap, string validatecode) // draw the verification code Image
{
Graphics G = graphics. fromimage (Bitmap); // obtain the Paster object
Font font = new font (fontfamily, fontsize, fontstyle. Bold); // set the font
G. drawstring (validatecode, Font, brushes. Black, posx, Posy); // draw the verification code Image
}
Finally, it is called.Copy codeThe Code is as follows: protected void page_load (Object sender, eventargs E)
{
String validatecode = createvalidatecode (); // generate a verification code
Bitmap bitmap = new Bitmap (imgwidth, imgheight); // generate a bitmap image
Disturbbitmap (Bitmap); // image background
Drewvalidatecode (bitmap, validatecode); // draw the verification code Image
Bitmap. Save (response. outputstream, imageformat. GIF); // Save the image and wait for the output
}
Validatecode. ASPX page complete
The rest is simple, creating a pageCopy codeThe Code is as follows: <asp: Image id = "image1" runat = "server" Height = "21px" width = "61px" imageurl = "~ /Default2.aspx "imagealign =" Middle "/>
Effect after running
When submitting the request, compare the value in the text box with session ["vcode"] = validatecode; // Save the verification code to check whether the input is correct.