Creates a new page that is designed to create a captcha picture validatecode.aspx
Its background CS file code is as follows:
Pageload
Copy Code code as follows:
private void Page_Load (object sender, System.EventArgs e)
{
String checkcode = Createrandomcode (4);
session["Checkcode"] = Checkcode;
CreateImage (Checkcode);
}
Where Createrandomcode is a custom function, and the parameter represents the number of verification code digits
Copy Code code as follows:
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,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 that is used to generate graphs
Copy Code code 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", 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 of these methods can change the background color of the resulting picture. The following for loop is used to generate some random horizontal lines
Add a <asp:Image> control to the page where you need to use the CAPTCHA, but point the ImageUrl to the page that generated the verification code.
Copy Code code as follows:
<asp:image runat= "Server" id= "Imagecheck" imageurl= "validatecode.aspx" ></asp:Image>