这里我们做一个小应用,就是绘制一个如下图所示的验证码图片。并且点击验证码的时候会自动切换。
实现思路如下:
- 通过Random生成随机数或字符及验证码
- 通过验证码内容长度生成指定大小的图片
- 获取生成图片的Graphics对象
- 定义验证码字体格式
- 通过指定字体将验证码绘制到图片
- 向图片上添加背景噪音线
- 添加前景噪音点
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 }
效果如下:
时间: 2024-10-24 06:57:54