Use C # To generate a verification code

Source: Internet
Author: User

First, add a page named code. aspx.
Add namespace

using System.IO;using System.Drawing.Imaging;using System.Drawing.Drawing2D;using System.Drawing;

Add page Initialization

Protected void page_load (Object sender, eventargs e) {// generate a string code = This. createrandomcode (4); // use session to save session ["checkcode"] = Code; // plot createimage (CODE );}

In the code above, createrandomcode is used to generate a random number of specified digits, while createimage is used to draw a pattern. Let's take a look at these two methods:

Createrandomcode:

public string CreateRandomCode(int codeCount){    string allChar = "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[] allCharArray = allChar.Split(',');    string randomCode = "";    int temp = -1;    Random rand = new Random();    for (int i = 0; i < codeCount; i++)    {        if (temp != -1)        {            rand = new Random(i * temp * ((int)DateTime.Now.Ticks));        }        int t = rand.Next(36);        if (temp != -1 && temp == t)        {            return CreateRandomCode(codeCount);        }        temp = t;        randomCode += allCharArray[t];    }    return randomCode;}

Createimage code:

Private void createimage (string checkcode) {int iwidth = (INT) (checkcode. length * 15); system. drawing. bitmap image = new system. drawing. bitmap (iwidth, 25); graphics G = graphics. fromimage (image); G. clear (color. white); // define the color [] C = {color. black, color. red, color. darkblue, color. green, color. orange, color. brown, color. darkcyan, color. purple}; // define the font string [] font = {"verdana", "Microsoft sans serif", "Comic Sans MS", "Arial", ""}; random Rand = new random (); // random output noise for (INT I = 0; I <50; I ++) {int x = Rand. next (image. width); int y = Rand. next (image. height); G. drawrectangle (new pen (color. lightgray, 0), X, Y, 1, 1) ;}// the verification code character for (INT I = 0; I <checkcode. length; I ++) {int cIndex = Rand. next (7); int findex = Rand. next (5); font F = new system. drawing. font (font [findex], 10, system. drawing. fontstyle. bold); brush B = new system. drawing. solidbrush (C [cIndex]); int II = 4; If (I + 1) % 2 = 0) {II = 2;} G. drawstring (checkcode. substring (I, 1), F, B, 3 + (I * 12), II);} // draw a border G. drawrectangle (new pen (color. black, 0), 0, 0, image. width-1, image. height-1); // output to the browser system. io. memorystream MS = new system. io. memorystream (); image. save (MS, system. drawing. imaging. imageformat. JPEG); response. clearcontent (); response. c; response. binarywrite (Ms. toarray (); G. dispose (); image. dispose ();}

The complete code is provided below

Using system; using system. data; using system. configuration; using system. collections; using system. web; using system. web. security; using system. web. ui; using system. web. UI. webcontrols; using system. web. UI. webcontrols. webparts; using system. web. UI. htmlcontrols; using system. io; using system. drawing. imaging; using system. drawing. drawing2d; using system. drawing; public partial class code: system. web. UI. page {prot Ected void page_load (Object sender, eventargs e) {// generate a string code = This. createrandomcode (4); // use session to save session ["checkcode"] = Code; // map createimage (CODE);} private void createimage (string checkcode) {int iwidth = (INT) (checkcode. length * 15); system. drawing. bitmap image = new system. drawing. bitmap (iwidth, 25); graphics G = graphics. fromimage (image); G. clear (color. white); // define the color [] C = {color. black, color. red, color. darkblue, color. green, color. orange, color. brown, color. darkcyan, color. purple}; // define the font string [] font = {"verdana", "Microsoft sans serif", "Comic Sans MS", "Arial", ""}; random Rand = new random (); // random output noise for (INT I = 0; I <50; I ++) {int x = Rand. next (image. width); int y = Rand. next (image. height); G. drawrectangle (new pen (color. lightgray, 0), X, Y, 1, 1);} // output the verification code characters of different fonts and colors for (INT I = 0; I <checkcode. length; I ++) {int cIndex = Rand. next (7); int findex = Rand. next (5); font F = new system. drawing. font (font [findex], 10, system. drawing. fontstyle. bold); brush B = new system. drawing. solidbrush (C [cIndex]); int II = 4; If (I + 1) % 2 = 0) {II = 2;} G. drawstring (checkcode. substring (I, 1), F, B, 3 + (I * 12), II);} // draw a border G. drawrectangle (New Pen (color. black, 0), 0, 0, image. width-1, image. height-1); // output to the browser system. io. memorystream MS = new system. io. memorystream (); image. save (MS, system. drawing. imaging. imageformat. JPEG); response. clearcontent (); response. c; response. binarywrite (Ms. toarray (); G. dispose (); image. dispose ();} Public String createrandomcode (INT codecount) {string allchar = ", 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 [] allchararray = allchar. split (','); string randomcode = ""; int temp =-1; random Rand = new random (); For (INT I = 0; I <codecount; I ++) {If (temp! =-1) {Rand = new random (I * temp * (INT) datetime. now. ticks);} int T = Rand. next (36); If (temp! =-1 & temp = T) {return createrandomcode (codecount);} temp = T; randomcode + = allchararray [T];} return randomcode ;}}
Related Article

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.