Create a page named VerificationCode. aspx
Using System;
Using System. Drawing;
Using System. Drawing. Imaging;
Namespace VerificationCodeDemo
{
Public partial class VerificationCode: System. Web. UI. Page
{
/// <Summary>
/// Page Initialization
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Protected void Page_Load (object sender, EventArgs e)
{
String verificationCode = CreateRandomCode (4 );
Session ["VerificationCode"] = verificationCode;
CreateImage (verificationCode );
}
/// <Summary>
/// Generate a random string mixed with numbers and characters
/// </Summary>
/// <Param name = "I"> Number of random characters </param>
/// <Returns> random string </returns>
Private string CreateRandomCode (int I)
{
String allChar = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
Char [] allCharArray = allChar. ToCharArray ();
String randomCode = string. Empty;
Random Rand = new random ();
For (Int J = 0; j <I; j ++)
{
Int K = Rand. Next (61 );
Randomcode + = allchararray. getvalue (k );
}
Return randomcode;
}
/// <Summary>
/// Generate the image Verification Code
/// </Summary>
/// <Param name = "verificationCode"> random string </param>
Private void CreateImage (string verificationCode)
{
Int iwidth = (int) (verificationCode. Length * 11.5 );
Bitmap image = new Bitmap (iwidth, 20 );
Graphics g = Graphics. FromImage (image );
Font f = new Font ("Arial", 10, FontStyle. Bold );
Brush B = new SolidBrush (Color. Azure); // letter white
G. Clear (Color. Brown); // background gray
G. drawstring (verificationcode, F, B, 3, 3 );
Pen blackpen = new pen (color. Black, 0 );
Random Rand = new random ();
System. Io. memorystream MS = new system. Io. memorystream ();
Image. Save (MS, imageformat. JPEG );
Response. clearcontent ();
Response. contenttype = "image/JPEG ";
Response. BinaryWrite (ms. ToArray ());
G. Dispose ();
Image. Dispose ();
}
}
}
Create another page named WebForm1.aspx
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "WebForm1.aspx. cs" Inherits = "VerificationCodeDemo. WebForm1" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> Verification code example </title>
<Script language = "javascript" type = "text/javascript">
Function check (){
Var v = document. getElementById ("image1 ");
V. setAttribute ('src', 'verificationcode. aspx? '+ Math. random ());
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<! -- Click the image or text to refresh. -->
<A href = "javascript: Check ()"> not clear </a>
</Div>
</Form>
</Body>
</Html>