程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 學習筆記:利用GDI+生成簡單的驗證碼圖片,學習筆記gdi

學習筆記:利用GDI+生成簡單的驗證碼圖片,學習筆記gdi

編輯:C#入門知識

學習筆記:利用GDI+生成簡單的驗證碼圖片,學習筆記gdi


學習筆記:利用GDI+生成簡單的驗證碼圖片

1 /// <summary> 2 /// 單擊圖片時切換圖片 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void pictureBox1_Click(object sender, EventArgs e) 7 { 8 Random r = new Random(); 9 string str = string.Empty; 10 //生成5位隨機數如 90531 11 for (int i = 0; i < 5; i++) 12 { 13 str += r.Next(0, 10); 14 } 15 Bitmap bitmap = new Bitmap(150, 40); 16 Graphics g = Graphics.FromImage(bitmap); 17 //預定義幾種字體樣式和顏色 18 string[] fonts = { "微軟雅黑", "宋體", "黑體", "隸書", "仿宋" }; 19 Color[] colors = { Color.Yellow, Color.Blue, Color.Black, Color.Red, Color.Orange }; 20 //因為每一數字的字體和顏色可能不同, 21 //因此循環將生成的隨機數每一數字繪制到圖片 22 for (int i = 0; i < str.Length; i++) 23 { 24 Point p = new Point(i * 30, 0); 25 g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]), p); 26 } 27 //循環在圖片范圍內繪制出50條線 28 for (int i = 0; i < 50; i++) 29 { 30 //保證線的起始點都在圖片范圍內 31 Point p1 = new Point(r.Next(0, bitmap.Width), r.Next(0, bitmap.Height)); 32 Point p2 = new Point(r.Next(0, bitmap.Width), r.Next(0, bitmap.Height)); 33 g.DrawLine(new Pen(Brushes.Green), p1, p2); 34 } 35 //添加一些像素點 36 for (int i = 0; i < 300; i++) 37 { 38 Point p1 = new Point(r.Next(0, bitmap.Width), r.Next(0, bitmap.Height)); 39 bitmap.SetPixel(p1.X, p1.Y, Color.Green); 40 } 41 //在winForm中用PictureBox中顯示出來 42 pictureBox1.Image = bitmap; 43 } View Code

 最終效果如下

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved