ASP. NET Verification Code
First, let's talk about the principle.
In a logon interface, place an image on the interface and add a new item named ValidateCode. aspx.
Add a new page and write the following code in the new page:
Private int codeLen = 4; // verification code length private int fineness = 85; // image definition private int imgWidth = 48; // Image Width private int imgHeight = 24; // Image 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 the starting coordinate X private int posY = 0; // draw the coordinate Y private string CreateValidateCode () // generate the verification code {string validateCode = ""; Random random = new Random (); // Random number object for (int I = 0; I <codeLen; I ++) // generate each {int n = random in a loop. next (10); // number validateCode + = n. toString ();} Session ["vcode"] = validateCode; // Save the verification code return validateCode; // return the verification code} private void DisturbBitmap (Bitmap bitmap) // image background {Random random = new Random (); // generate for (int I = 0; I <bitmap. width; I ++) // generate {for (int j = 0; j <bitmap. height; j ++) {if (random. next (90) <= this. fineness) bitmap. setPixel (I, j, Color. lightGray) ;}} private void DrewValidateCode (Bitmap bitmap, string validateCode) // draw the verification code image {Graphics g = Graphics. fromImage (bitmap); // obtain the Paster object Font font = new Font (fontFamily, fontSize, FontStyle. bold); // set the drawing font g. drawString (validateCode, font, Brushes. black, posX, posY); // draw Verification Code image}
Write the following in Page_Load (object sender, EventArgs e:
Protected void Page_Load (object sender, EventArgs e) {string validateCode = CreateValidateCode (); // generate the verification code Bitmap bitmap = new Bitmap (imgWidth, imgHeight ); // generate Bitmap image DisturbBitmap (bitmap); // image background DrewValidateCode (bitmap, validateCode); // draw the verification code image bitmap. save (Response. outputStream, ImageFormat. gif); // Save the image and wait for the output}
Finally, run the code and the following style appears: