asp.net建立位元影像產生驗證圖片類(驗證碼類)

來源:互聯網
上載者:User
代碼:

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;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.