如何使用GDI+來製做一個隨機的驗證碼dom
繪製驗證碼以前先要引用this
using System.Drawing; using System.Drawing.Drawing2D;
首先,先寫一個方法來取得驗證碼裏的字符串spa
1 string CreateCode(int len)//len是自定義驗證碼的長度 2 { 3 string str = "012ABCDEF34GHIJK56LMN789OPQabcRSTdefUVWghiXYZjklmnopqrstuvwxyz";//驗證碼所要用到的全部字符,這裏我用了字母和數字的組合 4 string code = ""; 5 Random r = new Random(); 6 7 for (int i = 0; i < len; i++) 8 { 9 int j = r.Next(0, str.Length - 1);//取得一個從0到字符串長度的隨機數 10 code += str[j];//拼接到驗證碼變量裏 11 } 12 13 return code; 14 }
而後用GDI+繪圖,繪製在一個pictureBox裏code
void CreateImage() { Bitmap bt = new Bitmap(109, 39); Graphics g = Graphics.FromImage(bt); Random r=new Random(); string s = CreateCode(4); Pen p = new Pen(Color.Silver); SolidBrush so = new SolidBrush(Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256)));//隨機顏色的單色畫刷 Font f = new Font("Arial", 22, FontStyle.Italic); //循環隨機畫200個像素點(干擾點) for (int i = 0; i < 200; i++) { int x = r.Next(0, bt.Width);//隨機產生像素點X座標 int y = r.Next(0, bt.Height);//隨機產生像素點Y座標 //隨機產生紅、綠、藍的顏色值 int red = r.Next(0, 256); int green = r.Next(0, 256); int blue = r.Next(0, 256); bt.SetPixel(x, y, Color.FromArgb(red, green, blue)); } g.DrawString(s, f, so, 10, 0); g.DrawRectangle(p, new Rectangle(0, 0, bt.Width - 1, bt.Height - 1)); this.pictureBox1.Image = bt; g.Dispose(); }
最後調用CreateImage()方法就能將一個隨機的驗證碼圖片顯示在pictureBox中了blog