C#,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 //1,生产随机对象Random,生成随机数和验证码 9 Random r = new Random(); 10 //随机产生验证码字符 11 string str = null; 12 for (int i = 0; i < 5; i++) 13 { 14 str += r.Next(0, 10).ToString(); 15 } 16 //MessageBox.Show(str); 17 18 //创建GDI对象 19 Bitmap bmp = new Bitmap(120, 40); //创建位图 20 Graphics g = Graphics.FromImage(bmp); //创建GDI 21 //颜色 22 Color[] cs = { Color.Red, Color.Blue, Color.Black, Color.BlueViolet, Color.Green, Color.DarkRed }; 23 24 //绘制验证码文本字符串 25 for (int i = 0; i < 5; i++) 26 { 27 //绘制字体 28 string[] typeface = { "微软雅黑", "黑体", "宋体", "仿宋", "隶书", "楷书" }; 29 Font font = new Font(typeface[r.Next(0, 6)], 20, FontStyle.Bold); 30 //颜色 31 //Color[] cs = { Color.Red, Color.Blue,Color.LightGray,Color.Gray,Color.Green,Color.GhostWhite }; 32 g.DrawString(str[i].ToString(), font, new SolidBrush(cs[r.Next(0, 6)]), new Point(i * 20, 0)); 33 } 34 35 //绘制干扰线 ,画直线 36 for (int i = 0; i < 30; i++) 37 { 38 39 Pen pen = new Pen(cs[r.Next(0, 3)], 1);//画笔 40 Point p1 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height)); 41 Point p2 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height)); 42 g.DrawLine(pen, p1, p2); 43 44 } 45 46 //设置像素点颜色 47 for (int i = 0; i < 500; i++) 48 { 49 bmp.SetPixel(r.Next(0, bmp.Width), r.Next(0, bmp.Height),Color.Black); 50 } 51 52 //将绘制图片嵌入pictureBox中 53 pictureBox1.Image = bmp; 54 55 56 }