用GDI+画验证码

时间:2021-06-29 23:22:37

1、新建一个窗体应用程序,在上面拖一个pictureBox对象,为其添加单击事件

2、创建GDI对象、产生随机数画入图片中、画线条、最后将图片到pictureBox中,代码如下:

 1  private void pictureBox1_Click(object sender, EventArgs e)
2 {
3 //创建GDI对象
4 Bitmap bmp = new Bitmap(150,40);
5 Graphics g = Graphics.FromImage(bmp);
6
7 //产生随机数并画入图片中
8 Random r = new Random();
9 string str = "";
10 for (int i = 0; i < 5;i++ )
11 {
12 str += r.Next(0,10);
13 }
14 for (int i = 0; i < 5; i++)
15 {
16 Point p = new Point(i*20,0);
17 string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" };
18 Color[] colors = { Color.Yellow,Color.Blue,Color.Black,Color.Red,Color.Pink};
19 g.DrawString(str[i].ToString(),new Font(fonts[r.Next(0,5)],20,FontStyle.Bold),new SolidBrush(colors[r.Next(0,5)]),p);
20
21 }
22
23 //画线
24 for (int i = 0; i < 20; i++)
25 {
26 Point p1 = new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
27 Point p2 = new Point(r.Next(0,bmp.Width),r.Next(0,bmp.Height));
28 g.DrawLine(new Pen(Brushes.Green),p1,p2);
29 }
30
31 //将图片镶嵌到pictureBox中
32 pictureBox1.Image = bmp;
33
34 }