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.