学习笔记:利用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位随机数如 9053111 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 }
最终效果如下