Randomly generate 6-bit image verification code

Source: Internet
Author: User
Tags border color

<summary>///PicHandler1 Summary description///</summary> public class Pichandler1:ihttphandler, irequires sessionstate {private String mcheckno = String.        Empty;        protected Imgbuilder _imgbuilder = new Imgbuilder ();        protected Vryimggen _imgbuildernew = new Vryimggen (); private string _text = String.        Empty;        private String _font = "Song Body";        private int _fontsize = 8;        private int _padding = 2;            public void ProcessRequest (HttpContext context) {Mcheckno = Discheckno (); Context.            session["Checkcode"] = Mcheckno;            This._imgbuilder.fontsize = this._fontsize;             this._imgbuilder.padding = this._padding; if (!string.            IsNullOrEmpty (This._font)) {this._imgbuilder.fonts = new string[] {This._font};            } this._imgbuildernew.chaoswight = 40;             This._imgbuildernew.fontsize = 25; this._imgbuildernew.padding = 3;           System.Drawing.Bitmap image = This._imgbuildernew.createimage (mcheckno);            System.IO.MemoryStream ms = new System.IO.MemoryStream (); Image.            Save (MS, System.Drawing.Imaging.ImageFormat.Jpeg); Context.            Response.clearcontent (); Context.            Response.ContentType = "Image/jpeg"; Context. Response.BinaryWrite (Ms.            ToArray ()); Context. session["Checkcode"] = mcheckno.tostring (); If IRequiresSessionState is not implemented, there will be an error here, and the picture context cannot be generated.        Response.End ();            }//Verification code generated protected string Discheckno () {String hash = Hashcode.getnext (); String checkno = String.            Empty;            Random rd = new random (DateTime.Now.Millisecond); for (int i = 0; i < 6; i++) {checkno + = hash. Substring (Rd. Next (1, hash.            Length-1), 1); } Checkno = Checkno.replace ("0", RD.) Next (1, 9).            ToString ()); Checkno = Checkno.replace ("O", RD. Next (1, 9).            ToString ()); Checkno = Checkno.replace ("O", RD. Next (1, 9).            ToString ());        return checkno;            } public bool IsReusable {get {return false; }        }    }

  

The class that is called

Using system;using system.drawing;using System.Text; <summary>///Vryimggen Summary description///</summary>public class vryimggen{public static string chinesechars = S Tring.     Empty; <summary>//English with Digital string///</summary> protected static readonly string englishornumchars = "0123456     789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";    Public Vryimggen () {rnd = new Random (unchecked ((int) DateTime.Now.Ticks));     }//<summary>//Global random number generator///</summary> private random rnd;    int length = 5;  <summary>///Verification code length (default 6 CAPTCHA Length)///</summary> public int Length {get {return length;    } set {length = value;}    } int fontSize = 20; <summary>///Verification Code font size (default 30 pixels for distortion effect, self-modifying)///</summary> public int FontSize {get        {return fontSize;}    set {fontSize = value;}    } int padding = 4; <summary>//frame complement (defaultRecognition 4 pixels)///</summary> public int Padding {get {return Padding;}    set {padding = value;}    } bool Chaos = true;        <summary>//Whether output dryness point (default output)///</summary> public bool Chaos {get {return Chaos;}    set {chaos = value;}    } Color chaoscolor = Color.lightgray; <summary>///output dry point color (default gray)///</summary> public color Chaoscolor {get {return chaos Color;    } set {Chaoscolor = value;}    } int chaoswight = 1;         <summary>///output dry point concentration///</summary> public int Chaoswight {get {return chaoswight;}    set {chaoswight = value;}    } Color backgroundcolor = Color.White; <summary>////Custom background color (default white)///</summary> public color BackgroundColor {get {return B Ackgroundcolor;    } set {backgroundcolor = value;} } color[] colors = {color.black, color.red, Color.darkblue, Color.green, Color.orange, Color.brown, Color.darkcyan, color.purple};        <summary>///custom random color array///</summary> public color[] Colors {get {return Colors;}    set {colors = value;}    } string[] fonts = {"Arial", "Georgia"};        <summary>////Custom font array///</summary> public string[] Fonts {get {return Fonts;}    set {fonts = value;}    } #region produce a waveform filter effect Private Const double PI = 3.1415926535897932384626433832795;     Private Const Double PI2 = 6.283185307179586476925286766559; <summary>//sine wave distorted picture (Edit by 51aspx.com)///</summary>//<param name= "srcbmp" > Picture path </param>//<param name= "Bxdir" > If distortion is selected for true</param>//<param name= "Nmultvalue" > the amplitude multiples of the waveform, the more The greater the degree of distortion, generally 3</param>//<param name= "Dphase" > Waveform starting phase, value range [0-2*PI] </param>//&LT;RETURNS&GT;&L T;/returns> Public System.Drawing.BitmapTwistimage (Bitmap srcbmp, bool Bxdir, double dmultvalue, double dphase) {System.Drawing.Bitmap destbmp = new Bi         TMap (Srcbmp.width, srcbmp.height);        Fills the bitmap background with white System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage (destbmp); Graph.        FillRectangle (New SolidBrush (System.Drawing.Color.White), 0, 0, destbmp.width, destbmp.height); Graph.         Dispose (); Double Dbaseaxislen = Bxdir?         (double) Destbmp.height: (double) destbmp.width;                for (int i = 0, i < destbmp.width; i++) {for (int j = 0; J < Destbmp.height; J + +) {                Double dx = 0; DX = Bxdir?                (PI2 * (double) j)/Dbaseaxislen: (PI2 * (double) i)/Dbaseaxislen;                DX + = Dphase;                 Double dy = math.sin (dx);                Gets the color of the current point int noldx = 0, Noldy = 0; NOLDX = Bxdir?                i + (int) (DY * dmultvalue): i; Noldy = Bxdir? J:j + (int) (DY * dmultvalue);                 System.Drawing.Color Color = Srcbmp.getpixel (i, j); if (noldx >= 0 && noldx < destbmp.width && noldy >= 0 && Noldy < DESTB Mp.                Height) {destbmp.setpixel (NOLDX, noldy, color);    }}} return destbmp; } #endregion///<summary>///<param Name= "code" > Verification Code </ param>//<returns></returns> public Bitmap createimage (string code) {int fsize = Fontsiz        E         int fwidth = fsize + Padding; int imagewidth = (int) (code.        Length * fwidth) + 4 + Padding * 2;         int imageheight = fsize * 2 + Padding * 2;         System.Drawing.Bitmap image = New System.Drawing.Bitmap (imageWidth-10, imageHeight-10);         Graphics g = graphics.fromimage (image);         G.clear (BackgroundColor); Adds a randomly generated dry point if (this) to the background. Chaos) {             Pen pen = new Pen (chaoscolor, 0);             int c = Chaoswight * 10; for (int i = 0; i < C; i++) {int x = rnd. Next (image.                Width); int y = rnd. Next (image.                 Height);            G.drawrectangle (pen, x, Y, 1, 1);         }} int left = 0, top = 0, Top1 = 1, top2 = 1;        int n1 = (imageheight-fontsize-padding * 2);        int n2 = N1/4;        Top1 = n2;         Top2 = n2 * 2;        Font F;         Brush b;         int CIndex, Findex; Random font and color verification code characters for (int i = 0; i < code. Length; i++) {CIndex = rnd.            Next (colors.length-1); Findex = rnd.             Next (fonts.length-1);            f = new System.Drawing.Font (Fonts[findex], fsize, System.Drawing.FontStyle.Bold);             b = new System.Drawing.SolidBrush (Colors[cindex]);            if (i% 2 = = 1) {top = TOP2; } else {top = TOP1;             } left = i * fwidth; g.DrawString (code.        Substring (i, 1), F, B, left, top); }//Draw a border border color of Color.gainsboro g.drawrectangle (new Pen (Color.gainsboro, 0), 0, 0, image. Width-1, image.        HEIGHT-1);         G.dispose ();         Generate Waveform (ADD by 51aspx.com) image = Twistimage (image, True, 8, 4);    return image;    }///<summary>//Generate random character codes///</summary>//<param name= "Codelen" > String length </param> <param name= "Zhcharscount" > Chinese characters </param>//<returns></returns> public string Createve         Rifycode (int codelen, int zhcharscount) {char[] chs = new Char[codelen];        int index; for (int i = 0; i < Zhcharscount; i++) {index = rnd.            Next (0, Codelen);            if (chs[index] = = ' + ') chs[index] = Createzhchar ();        Else-I.;      } for (int i = 0; i < Codelen; i++)  {if (chs[i] = = ' + ') chs[i] = Createenornumchar (); } return new string (CHS, 0, CHS.    Length); }///<summary>//Generate random character codes of default length 5///</summary>//<returns></returns> Public St    Ring Createverifycode () {return Createverifycode (Length, 0); }//<summary>//Generate English or numeric characters///</summary>//<returns></returns> protected Cha R Createenornumchar () {return englishornumchars[rnd.    Next (0, englishornumchars.length)]; }//<summary>//Generate kanji characters///</summary>//<returns></returns> protected char C Reatezhchar () {//If a Chinese character set is provided, the Chinese character set is selected for the kanji if (chinesechars.length > 0) {return Chinesecha Rs[rnd.        Next (0, chinesechars.length)];             }//If the Chinese character set is not provided, then the Chinese character (else {byte[] bytes = new Byte[2] is constructed according to the coding rules of the GB2312 Simplified Chinese encoding table;           The first byte value is between 0xb0, 0xf7 Bytes[0] = (byte) rnd.            Next (0xb0, 0xf8); The second byte value is 0xa1, 0xfe between bytes[1] = (byte) rnd.             Next (0xa1, 0xff); Decodes the Chinese character string str1 = Encoding.GetEncoding ("gb2312") according to the byte array of the Chinese character coding.             GetString (bytes);        return str1[0]; }    } }

  

Randomly generate 6-bit image verification code

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.