The first is to create a new authentication code page validatecode.aspx
Defining variables that's good for later revisions.
Copy Code code as follows:
private int codelen = 4;//Verification Code length
private int fineness = 85;//picture sharpness
private int imgwidth = 48;//picture width
private int imgheight = 24;//picture height
private string fontFamily = "Times New Roman";//font name
private int fontsize = 14;//font Size
private int fontstyle = 0;//font style
private int posx = 0;//Draw start coordinates x
private int posy = 0;//Draw coordinate y
private string Createvalidatecode ()//Generating Verification code
{
String validatecode = "";
Random Random = new Random ()//Random Number Object
for (int i = 0; i < Codelen; i++)//loops generate each digit value
{
int n = random. Next (10);//number
Validatecode + + n.tostring ();
}
session["Vcode"] = validatecode;//Save authentication Code
Return validatecode;//back Verification code
}
private void Disturbbitmap (Bitmap Bitmap)//image background
{
Random Random = new Random ();//generated by random number
for (int i = 0; i < bitmap. Width; i++)//Through the loop nesting, pixel-by-point generation
{
for (int j = 0; J < bitmap. Height; J + +)
{
if (random. Next (<=) this.fineness)
Bitmap. SetPixel (I,j,color.lightgray);
}
}
}
private void Drewvalidatecode (Bitmap bitmap,string Validatecode)//To draw a CAPTCHA image
{
Graphics g = graphics.fromimage (bitmap);//Get the drawing object
Font font = new Font (fontfamily,fontsize,fontstyle.bold);//Set Drawing font
g.DrawString (Validatecode,font,brushes.black,posx,posy);//Draw captcha image
}
The last is to call the
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
String validatecode = Createvalidatecode ();//Generate Verification code
Bitmap Bitmap = new Bitmap (imgwidth,imgheight);//Generate Bitmap image
Disturbbitmap (bitmap); Image background
Drewvalidatecode (Bitmap,validatecode);//Draw captcha image
Bitmap. Save image, wait for output (response.outputstream,imageformat.gif);
}
Validatecode.aspx Page Complete
The rest is simple. Create a new page
Copy Code code as follows:
<asp:image id= "Image1" runat= "Server" height= "21px" width= "61px" imageurl= "~/default2.aspx" imagealign= "Middle"/ >
The effect after the run as shown:
When submitting the value in the text box and session["vcode"] = validatecode;//Save the verification code comparison can determine whether the input is correct