一個C#生成簡單驗證碼的類
一個C#生成簡單驗證碼的類
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls.WebParts; using System.Data; using System.Web.Security; using System.Collections; using System.Drawing;public partial class Code : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["label"] == null) { string str = ""; string[] code = {"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","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"};
//隨機產生字符串 Random rand = new Random(); for (int i = 0; i < 4; i++) { str = str + code[rand.Next(0, code.Length)]; } CreateImage(str); foreach (var s in str) { str += s; } Session["str"] = str; //foreach (string s in str) //{ // str += s; //} //Session["str"] = str; // Label1.Text = str; // Session["label"] = Label1.Text; } } //畫驗證圖片 private void CreateImage(string checkcode) { if (checkcode == null || checkcode.Length <= 0) return; int width = (int)(checkcode.Length * 25); System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling(checkcode.Length*32.5), 40); Graphics g = Graphics.FromImage(image); g.Clear(Color.White); //定義顏色 Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple }; //定義字體 string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋體" }; Random rand = new Random(); //畫圖片的背景線 for (int i = 0; i < 70; i++) { int x = rand.Next(image.Width); int y = rand.Next(image.Height); g.DrawLine(new Pen(Color.LightGray, 1), x, y, 10, 20); } //輸出不同字體和顏色的驗證碼字符 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], 23, System.Drawing.FontStyle.Bold);//23表示字體大小 Brush brush = new System.Drawing.SolidBrush(c[cindex]); int ii = 4; if ((i + 1) % 2 == 0) { ii = 2; } g.DrawString(checkcode.Substring(i, 1), f, brush, 15 + (i * 12), ii); } //畫邊框,畫圖片的邊框線 g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1); //輸出到瀏覽器 System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); HttpContext.Current.Response.ContentType = "image/jpeg"; HttpContext.Current.Response.BinaryWrite(ms.ToArray()); g.Dispose(); image.Dispose(); }
}</pre>
本文由用戶 pb44 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!