C# GDI绘制验证码

步骤:
1.通过Random生成随机数或字符及验证码
2.通过验证码内容长度生成指定大小的图片
3.获取生成图片的Graphics对象
4.定义验证码字体格式
5.通过指定字体将验证码绘制到图片
6.向图片上添加背景噪音线
7.添加前景噪音点
 
C#  GDI绘制验证码
 1  private void pictureBox1_Click(object sender, EventArgs e)
 2         {
 3             Random r = new Random();
 4             string str = null;
 5             for (int i = 0; i < 5; i++)
 6             {
 7                 int rNumber = r.Next(0, 10);
 8                 str += rNumber;
 9             }
10             //MessageBox.Show(str);
11             //创建GDI对象
12             Bitmap bmp=new Bitmap(120,50);
13             Graphics g = Graphics.FromImage(bmp);
14 
15             for (int i = 0; i < 5; i++)
16             {
17                 Point p=new Point(i*20,0);
18                 string [] fonts={"微软雅黑","宋体","黑体","隶书","仿宋"};
19                 Color [] colors={Color.Yellow,Color.Blue,Color.Black,Color.Red,Color.Green};
20                 g.DrawString(str[i].ToString(),new Font(fonts[r.Next(0,4)],20,FontStyle.Bold),new SolidBrush(colors[r.Next(0,5)]),p);
21             }
22             //绘制线条,线条不能超出验证码的范围
23             for (int i = 0; i < 30; i++)
24             {
25                 Point p1=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
26                 Point p2=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
27                 g.DrawLine(new Pen(Brushes.Green), p1, p2);
28             }
29 
30             for (int i = 0; i < 1000; i++)
31             {
32                 Point p=new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
33                 bmp.SetPixel(p.X, p.Y, Color.Black);
34             }
35             //将图片镶嵌到PictureBox中
36             pictureBox1.Image = bmp;
37 
38         }
View Code

 

C# GDI绘制验证码

上一篇:C#基础之------for与foreach的区别


下一篇:C# 内存理论与实践