1. 程式人生 > >【5】GDI+ 生成驗證碼

【5】GDI+ 生成驗證碼

splay 小應用 eric gen 前景 num 微軟 param graphic

這裏我們做一個小應用,就是繪制一個如下圖所示的驗證碼圖片。並且點擊驗證碼的時候會自動切換。

技術分享

實現思路如下:

  1. 通過Random生成隨機數或字符及驗證碼
  2. 通過驗證碼內容長度生成指定大小的圖片
  3. 獲取生成圖片的Graphics對象
  4. 定義驗證碼字體格式
  5. 通過指定字體將驗證碼繪制到圖片
  6. 向圖片上添加背景噪音線
  7. 添加前景噪音點
技術分享
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using
System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace 使用GDI繪制驗證碼 12 { 13 public partial class Form1 : Form 14 { 15 public Form1() 16 { 17 InitializeComponent(); 18 } 19 20 21 /// <summary>
22 /// 點擊更換驗證碼 23 /// </summary> 24 /// <param name="sender"></param> 25 /// <param name="e"></param> 26 private void pictureBox1_Click(object sender, EventArgs e) 27 { 28 Random r = new Random(); 29 string str = null
; 30 for (int i = 0; i < 5; i++) 31 { 32 int rNumber = r.Next(0, 10); 33 str += rNumber; 34 } 35 // MessageBox.Show(str); 36 //創建GDI對象 37 Bitmap bmp = new Bitmap(150, 40); 38 Graphics g = Graphics.FromImage(bmp); 39 40 for (int i = 0; i < 5; i++) 41 { 42 Point p = new Point(i * 20, 0); 43 string[] fonts = { "微軟雅黑", "宋體", "黑體", "隸書", "仿宋" }; 44 Color[] colors = { Color.Yellow, Color.Blue, Color.Black, Color.Red, Color.Green }; 45 g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]), p); 46 } 47 48 for (int i = 0; i < 20; i++) 49 { 50 Point p1=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height)); 51 Point p2=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height)); 52 g.DrawLine(new Pen(Brushes.Green), p1, p2); 53 } 54 55 for (int i = 0; i < 500; i++) 56 { 57 Point p=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height)); 58 bmp.SetPixel(p.X, p.Y, Color.Black); 59 } 60 61 62 //將圖片鑲嵌到PictureBox中 63 pictureBox1.Image = bmp; 64 } 65 } 66 }
View Code

效果如下:

技術分享

【5】GDI+ 生成驗證碼