1. First, the event code in Page_Load of the aspx file of the background verification code:
Copy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Drawing;
Namespace online student Examination System
{
Public partial class AjaxAutoCode: System. Web. UI. Page
{
// Verify the number
Public string authcode = string. Empty;
Protected void Page_Load (object sender, EventArgs e)
{
# Region the first method to generate a verification code
Random random = new Random ();
Authcode = random. Next (1111,999 9). ToString ();
// Construct an image
Bitmap image = new Bitmap (authcode. Length * 12, 25 );
// Create a canvas
Graphics g = Graphics. FromImage (image );
Try
{
G. Clear (Color. White );
For (int I = 0; I <25; 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 );
// Link two-point lines
G. DrawLine (new Pen (Color. Silver), x1, y1, x2, y2 );
}
Font font = new Font ("Arial", 12, FontStyle. Bold | FontStyle. Italic );
System. Drawing. Drawing2D. LinearGradientBrush brush = new System. Drawing. Drawing2D. LinearGradientBrush (
New Rectangle (0, 0, image. Width, image. Height), Color. Blue, Color. DarkBlue, 1.2f, true );
G. DrawString (authcode, font, brush, 2, 2 );
// Foreground Noise
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 ()));
}
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 );
Ms. WriteTo (this. Response. OutputStream );
Ms. Close ();
This. Response. ContentType = "image/gif ";
}
Finally
{
Image. Dispose ();
G. Dispose ();
}
# Endregion
}
}
}
2. Define a JS function on the page where the verification code is displayed.Copy codeThe Code is as follows: function fGetCode ()
{
Document. getElementById ("getcode"). src = "Default2.aspx? "+ Math. random ();
}
3. Edit the front-end page aspx. The following is the code snippet of the front-end page.Copy codeThe Code is as follows: <label> Verification Code </label>
<Asp: TextBox ID = "txt_checkCode" runat = "server" Width = "178px"> </asp: TextBox>
<a href =" javascript: fGetCode () "> change Verification Code </a>