通过GDI+绘制 验证码

只为了记录下自己的学习历程,方便日后查看

现在开始言归正传,以下为其完整代码附上

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 
11 namespace _06GDI_绘制验证码
12 {
13     public partial class Form1 : Form
14     {
15         public Form1()
16         {
17             InitializeComponent();
18         }
19 
20         private void pictureBox1_Click(object sender, EventArgs e)
21         {
22             //用户生成随机码
23             Random r = new Random();
24             //用于遍历验证码的序列
25             string str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
26             //存储验证码
27             string code = "";
28             for (int i = 0; i < 5; i++)
29             {
30                 //随机从字符串序列中随机生成一个字符,并将其添加到验证码中
31                 code += str[r.Next(0,str.Length)];
32 
33             }
34             //创建位图对象,Bitmap继承于Image类
35             Bitmap bitimage = new Bitmap(140,30);
36             Graphics gra = Graphics.FromImage(bitimage);
37             for (int i = 0; i < 5; i++)
38             {
39                 //通过点,设置每个字体的宽度
40                 Point point = new Point(i*20,0);
41                 //字体数组,用于验证码中产生不同随机字体,
42                 string[] fonts = { "幼圆", "宋体", "仿宋", "楷体", "Times New Roman" };
43                 //颜色数组,用于验证码中产生不同颜色的字。
44                 Color[] colors = {Color.Black,Color.Blue,Color.Brown,Color.Chocolate,Color.DarkSlateBlue};
45                 //将生成的验证码字符通过GDI对象绘制出,调用DrawString()方法
46                 gra.DrawString(code[i].ToString(),new Font(fonts[r.Next(5)],25,FontStyle.Bold),new SolidBrush(colors[r.Next(5)]),point);
47 
48             }
49             //在验证码上添加部分线,使其不那么清晰
50            
51             for (int i = 0; i < 30; i++)
52             {
53                 Point p1=new Point(r.Next(bitimage.Width),r.Next(bitimage.Height));
54                 Point p2=new Point(r.Next(bitimage.Width),r.Next(bitimage.Height));
55                 Pen pen = new Pen(Brushes.Blue);
56                 gra.DrawLine(pen,p1,p2);//绘制线条
57             }
58             //在验证码上添加部分点,使其不那么清晰
59             for (int i = 0; i < 30; i++)
60             {
61                 Point p = new Point(r.Next(bitimage.Width),r.Next(bitimage.Height));
62                 bitimage.SetPixel(p.X, p.Y, Color.Black);//绘制点
63 
64             }
65                 picCon.Image = bitimage;//将所绘制的验证码添加到picboxs上
66               
67             
68            
69         }
70     }
71 }
GDI+ 绘制验证码

 

以下为运行结果图

 

posted @ 2016-03-21 12:58  PlutoZ300  阅读(157)  评论(0编辑  收藏  举报