asp.net how to generate a picture verification code (simple)

Source: Internet
Author: User
Tags rand
Asp.net| Verification Code

Create a new page image.aspx and add namespaces:

Using System.Drawing.Imaging;
Using System.IO;

Then copy the following code into the Page_Load event:

Generate a 4-bit verification code
string tmp = Rndnum (4);
HttpCookie a = new HttpCookie ("Imagev", TMP);
Response.Cookies.Add (a);
This. Validatecode (TMP);

Next, add two methods to the page:

private void Validatecode (String vnum)
{
Bitmap Img=null;
Graphics G=null;
MemoryStream Ms=null;

   int gheight=vnum.length*12;
   img=new Bitmap (gheight,25);
   g=graphics.fromimage (IMG);
  //Background color
   g.clear (color.white);
  //Text font
   font f=new font ("Arial black");
  //Text color
   solidbrush s=new SolidBrush (color.black);
   g.drawstring (vnum,f,s,3,3);
   ms=new MemoryStream ();
   Img.save (ms,imageformat.jpeg);
   response.clearcontent ();
   response.contenttype= "Image/jpeg";
   Response.BinaryWrite (Ms. ToArray ());
  
   g.dispose ();
   Img.dispose ();
   Response.End ();
 }

private string rndnum (int vcodenum)
{
String vchar= "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,v,w,x,y,z";
String[] Vcarray=vchar.split (new Char [] {', '});
String Vnum= "";
int temp=-1;

Random rand=new Random ();

for (int i=1;i<vcodenum+1;i++)
{
if (temp!=-1)
{
Rand=new Random (i*temp*unchecked (int) DateTime.Now.Ticks));
}

int T=rand. Next (35);
if (temp!=-1&&temp==t)
{
Return Rndnum (Vcodenum);
}
temp=t;
VNUM+=VCARRAY[T];
}
return vnum;
}

If you want to generate a CAPTCHA on the page a.aspx, add a picture control to the page, assuming it is named: ImageButton1, and then write the following code in the Page_Load event:

Imagebutton1.imageurl = "image.aspx";

This can generate verification code, image.aspx page can be put anywhere, but pay attention to Imagebutton1.imageurl to write to, the same level can directly write image.aspx, write on the first. /image.aspx, it's very convenient.




Related Article

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.