首页 > 代码库 > 学习笔记:利用GDI+生成简单的验证码图片

学习笔记:利用GDI+生成简单的验证码图片

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03


学习笔记:利用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

 最终效果如下

技术分享

参考页面:http://qingqingquege.cnblogs.com/p/5933752.html

学习笔记:利用GDI+生成简单的验证码图片