本文提供一個asp.net生成驗證圖片的類,功能是顯示簡單的字符串,大家參考使用吧
代碼: 代碼如下: public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; //創建位圖,並且給指定邊框的寬高 using (Image img=new Bitmap(80,25)) { //創建畫家對象,在img對象畫字符串 using (Graphics g=Graphics.FromImage(img)) { //設置位圖的背景顏色,默認是黑色 g.Clear(Color.White); //設置驗證碼的寬高, img.Width-1, img.Height-1主要是背景顏色覆蓋了邊框線 g.DrawRectangle(Pens.Black, 0, 0, img.Width-1, img.Height-1); //傳100個噪點,傳畫家對象,位圖對象 DrawPoint(100, g, img); //畫4個驗證碼的字符串 string vcode=GetCode(4);//vcode這裡可以賦值給Cookie g.DrawString(vcode, new Font("Arial", 14, FontStyle.Strikeout | FontStyle.Strikeout), // FontStyle字體的樣式,多個樣式,需要|線 Brushes.Black, new RectangleF(r.Next(20), r.Next(7), img.Width, img.Height)); img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//保存驗證碼對象,指定是Jpeg格式 } } } //畫噪點方法 void DrawPoint(int point,Graphics g,Image img) { for (int i = 0; i < point; i++) { int x = r.Next(img.Width); int y = r.Next(img.Width); g.DrawLine(Pens.Red, new Point(x, y), new Point(x+2, y+2)); } } //隨機數 Random r = new Random(); //畫字符創 string GetCode(int point) { string txtStr = "ASF2345WE5R9F3HMBCZ455K";//這裡的string字符串將會轉成 char數組,阿拉伯數字1和小寫字母l最好別寫在裡面,會搞胡亂。 char[] charArr = txtStr.ToArray(); int num = 0; string code = ""; for (int i = 0; i <point; i++) { num = r.Next(charArr.Length); code +=charArr[num]; } return code; }