On the realization of image verification code

Source: Internet
Author: User
Verification Code

First. Two pages login.aspx and gif.aspx.

Second. The URL of the image control for the Login.aspx page is specified as gif.aspx.

Third, the Gif.aspx page code is as follows:

private void Page_Load (object sender, System.EventArgs e)
{
String strnum = Randnum (4);
session["Test"] = Strnum;
Validatecode (Strnum);
viewstate["Test"] = Strnum;
}

<summary>
Generate random numbers
</summary>
<param name= "Inum" > Seed </param>
<returns></returns>
<author>tianzm</author>

private string randnum (int inum)
{
String Strchar = "0,1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
string[] strary = Strchar.split (', ');
String strnum = "";
System.Random obj = new Random ();
for (int i=0; i<inum; i++)
{
int index = obj. Next (strary.length);
Strnum = Strnum + Strary[index];
}
return strnum;

Here you can encrypt the random numbers that are generated.
}

<summary>
Re-draw image generation
</summary>
<param name= "Strnum" > Verification Code </param>
<author>tianzm</author>

private void Validatecode (string strnum)
{
System.Drawing.Bitmap img = null;
System.Drawing.Graphics g = null;
System.IO.MemoryStream ms = NULL;
int iwidth = convert.toint16 (strnum.length * 11.5);
img = new Bitmap (iwidth,20);
g = Graphics.fromimage (IMG);
g.DrawString (Strnum, New Font ("Arial"), (New SolidBrush (Color.Blue)), 3, 3);
ms = new MemoryStream ();
Img. Save (ms,imageformat.png);
Response.clearcontent ();
Response.ContentType = "Image/png";
Response.BinaryWrite (Ms. ToArray ());
G.dispose ();
Img. Dispose ();
Response.End ();
}

On the Login.aspx page, verify the following:

String strtemp = session["Test"]. ToString ();
Session.Abandon ();
viewstate["Testnum"] = strtemp;
if (this. TextBox1.Text = = viewstate["Testnum"]. ToString ())
{
This. Label1.Text = "Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.