代碼:
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這裡可以賦值給Cookieg.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;}