概括
新建一个Windows窗体应用项目,在界面设计上新增一个PictureBox控件用于展示图片验证码,新增一个Button按钮用于响应生成图片验证码
代码
(1) 利用Random类随机生成验证码,如 00F2、D3G2
public string CheckCode()
{
int codeNum = 4;//生成4位验证码
int number; //随机生成数字
char code; // 验证码的每一位符号
string checkCode = String.Empty;
Random random = new Random();
for(int i = 0; i < codeNum; i++)
{
number = random.Next();
if (number % 2 == 0) //如果是偶数,就指定生成符号为数字
code = (char)('0' + (char)(number % 10));
else //否则指定生成符号为大写字母
code = (char)('A' + (char)(number % 10));
checkCode += " " + code.ToString();
}
return checkCode;
}
(2)将验证码绘制成图片
public void CodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty) return;
// 指定验证码图片大小,height width
Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 9.5)), 22);
Graphics g = Graphics.FromImage(image);
Random random = new Random();
g.Clear(Color.Yellow);// 清空图片背景色,即指定验证码的背景色
//随机画图片的前景噪音线
for(int i = 0; i < 3; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
}
//画验证码,红色字体
Font font = new Font("Arial", 12, (FontStyle.Bold));
g.DrawString(checkCode, font, new SolidBrush(Color.Red), 2, 2);
//随机画图片的前景噪音点
for(int i = 0; i < 150; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x,y,Color.FromArgb(random.Next()));//设置指定像素的颜色
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
this.pictureBox1.Width = image.Width;
this.pictureBox1.Height = image.Height;
this.pictureBox1.BackgroundImage = image;
}
(3)在窗体初始化和按钮点击时分别调用 CodeImage方法
public Form1()
{
InitializeComponent();
CodeImage(CheckCode());
}
private void button1_Click(object sender, EventArgs e)
{
CodeImage(CheckCode());
}