如何用GDI+画个验证码

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

如何使用GDI+来制作一个随机的验证码

绘制验证码之前先要引用

using System.Drawing;
using System.Drawing.Drawing2D;

首先,先写一个方法来取得验证码里的字符串

 1 string CreateCode(int len)//len是自定义验证码的长度
2 {
3 string str = "012ABCDEF34GHIJK56LMN789OPQabcRSTdefUVWghiXYZjklmnopqrstuvwxyz";//验证码所要用到的所有字符,这里我用了字母和数字的组合
4 string code = "";
5 Random r = new Random();
6
7 for (int i = 0; i < len; i++)
8 {
9 int j = r.Next(0, str.Length - 1);//取得一个从0到字符串长度的随机数
10 code += str[j];//拼接到验证码变量里
11 }
12
13 return code;
14 }

然后用GDI+绘图,绘制在一个pictureBox里

void CreateImage()
{
Bitmap bt
= new Bitmap(109, 39);
Graphics g
= Graphics.FromImage(bt);

Random r
=new Random();
string s = CreateCode(4);
Pen p
= new Pen(Color.Silver);

SolidBrush so
= new SolidBrush(Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256)));//随机颜色的单色画刷
Font f = new Font("Arial", 22, FontStyle.Italic);

//循环随机画200个像素点(干扰点)
for (int i = 0; i < 200; i++)
{
int x = r.Next(0, bt.Width);//随机产生像素点X坐标
int y = r.Next(0, bt.Height);//随机产生像素点Y坐标
//随机产生红、绿、蓝的颜色值
int red = r.Next(0, 256);
int green = r.Next(0, 256);
int blue = r.Next(0, 256);
bt.SetPixel(x, y, Color.FromArgb(red, green, blue));
}

g.DrawString(s, f, so,
10, 0);
g.DrawRectangle(p,
new Rectangle(0, 0, bt.Width - 1, bt.Height - 1));
this.pictureBox1.Image = bt;
g.Dispose();

}

最后调用CreateImage()方法就能将一个随机的验证码图片显示在pictureBox中了