C # basic review: Use GDI + to draw verification Codes

Source: Internet
Author: User

The verification code can be seen on many webpages that require users to log on or make comments. Traditionally, images with different numbers or characters are combined to achieve the effect. However, it is obvious that this method is not flexible and requires a large number of images for material preparation.

Currently, automatic generation is generally used. The verification code is a single image, rather than a combination of multiple images. In. Net, it can be implemented through GDI +, and you may find it very troublesome, but as long as you follow me again, you will find it very simple.
Now, you can create a simple verification code. (This section does not describe how to use the GDI + technology. For more information, see here)
1. To generate a verification code, the key is to generate a random number (the random number here refers to the combination of numbers and letters ).
Do numbers and characters both use ASCII Code for Representation? Therefore, there are many ways to generate random numbers containing letters and numbers, not only by providing all numbers and letters in advance. If you have any good solutions, I hope you can give us some advice. Today I want to introduce a very simple method. Let's look at the Code directly:

Generate random number
Public static string Generate (RandomGeneratorStyle style, int length)
{
String strValidateString = "";
Random rnd = new Random ();
String strValidateStringSource;
Switch (style)
{
Case RandomGeneratorStyle. Number:
StrValidateStringSource = "0123456789 ";
Break;
Case RandomGeneratorStyle. NumberAndChar:
StrValidateStringSource = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
Break;
Case RandomGeneratorStyle. NumberAndCharIgnoreCase:
StrValidateStringSource = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
Break;
Default:
StrValidateStringSource = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
Break;
}
For (int I = 0; I <length; I ++)
{
StrValidateString + = strValidateStringSource [rnd. Next (strValidateStringSource. Length-1)];
}
Return strValidateString;
}

There is a RandomGeneratorStyle above, which is an enumeration I wrote to indicate which verification code to generate.

RandomGeneratorStyle
Public enum RandomGeneratorStyle
{
/// <Summary>
/// Only numbers
/// </Summary>
Number,
/// <Summary>
/// Contains numbers and uppercase/lowercase characters
/// </Summary>
NumberAndChar,
/// <Summary>
/// Contains numbers and uppercase characters
/// </Summary>
NumberAndCharIgnoreCase
}

2. With these numbers, you will be involved in painting. Of course, the paint and watercolor pens are not used here, but the GDI + is used.
What kind of verification code do we usually see? Is it a rectangle? Are there random numbers in the rectangle? The next step is to use the GDI + technology to draw the generated random number into a rectangle.
There is only one method to use: Graphics. DrawString (). If you are not familiar with it, you can check the introduction of this method online. The Code is as follows:

Draw Verification Code
Public static void Generate (RandomGeneratorStyle style, int length, Page curPage)
{
Bitmap bmp = new Bitmap (int) Math. Ceiling (length * 12.5), 20); // create an image object
Graphics g = Graphics. FromImage (bmp); // use this image object to generate a canvas"
String strCode = RandomGenerator. Generate (style, length); // Generate a random number
CurPage. Session ["yzmCode"] = strCode; // save it to the Session to verify the service. You can also store it elsewhere, as long as you can obtain
Font font = new Font ("Arial", 12, FontStyle. Bold | FontStyle. Italic); // set the Font color
SolidBrush brush = new SolidBrush (Color. White); // create a paint brush. So far, we have prepared the canvas, paint brush, and data.
G. DrawString (strCode, font, brush, 0, 0); // a key step for plotting.
Bmp. Save (curPage. Response. OutputStream, ImageFormat. Jpeg); // Save it as an output stream. Otherwise, the output stream cannot be displayed on the page.
G. Dispose (); // release the resource
}

Now, you can test its effect. To call the above method, we must input a current Page object. Therefore, we can create a new Page named yzm. aspx. Then, call this method in PageLoad. In this way, we can see it. As shown in 1:


Figure 1 Verification Code

If you need to display it in the img element, it is also very simple. You just need to set src to yzm. aspx.
Finally, we will introduce how to perform verification. (If it is only displayed and not verified, it cannot be called a verification code .)
Careful friends should have discovered that in the method of drawing the verification code, I set a Session. If verification is required, it is compared with the Session set during the painting. The Code is as follows:

Verification Method
Public static bool Validate (string codeToBeValidate, Page curPage)
{
If (curPage. Session ["yzmCode"]! = Null)
{
Return curPage. Session ["yzmCode"]. ToString () = codeToBeValidate;
}
Else
Return false;
}

In this way, you can generate a verification code. If you want to generate beautiful verification codes, you need to use your own brains during the painting process.

Author: stg609
Source: http://stg609.cnblogs.com/
The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.

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.