C#实现公式计算验证码的案例分享实现代码

实现代码

/// <summary>

/// 生成验证码图片

/// </summary>

/// <param name="code"></param>

/// <returns></returns>

public byte[] GenerateImg(string code)

{

Bitmap image = new Bitmap(code.Length * 25, 25);

Graphics g = Graphics.FromImage(image);

try

{

//清空图片背景色

g.Clear(Color.White);

//增加背景干扰线

Random random = new Random();

for (int i = 0; i < 30; 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.FromArgb(186, 212, 231)), x1, y1, x2, y2);

}

//定义验证码字体

Font font = new Font("黑体", 12, (FontStyle.Bold | FontStyle.Italic));

//定义验证码的刷子,这里采用渐变的方式,颜色可自定义

LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.FromArgb(67, 93, 230), Color.FromArgb(70, 128, 228), 1.5f, true);

//增加干扰点

for (int i = 0; i < 100; i++)

{

int x = random.Next(image.Width);

int y = random.Next(image.Height);

//颜色可自定义

image.SetPixel(x, y, Color.FromArgb(random.Next()));

}

//将验证码写入图片

g.DrawString(code, font, brush, random.Next(5, 50), random.Next(5, 10));

//图片边框

g.DrawRectangle(new Pen(Color.FromArgb(93, 142, 228)), 0, 0, image.Width - 1, image.Height - 1);

//保存图片数据

MemoryStream stream = new MemoryStream();

image.Save(stream, ImageFormat.Jpeg);

return stream.ToArray();

}

finally

{

g.Dispose();

image.Dispose();

}

}

private void button1_Click(object sender, EventArgs e)

{

GenerateCode();

}

private void GenerateCode()

{

string[] symbols = new string[]{

"+","-","*"

};

Random random = new Random();

string code = random.Next(0, 99) + symbols[random.Next(0,symbols.Length)] + random.Next(0, 99);

//这里拿到结果用来验证

DataTable dt = new DataTable();

string result = Convert.ToString(dt.Compute(code, null));

label1.Text = result;

byte[] bytes = GenerateImg(code);

MemoryStream ms = new MemoryStream(bytes);

Image image = System.Drawing.Image.FromStream(ms);

pictureBox1.Image = image;

}

代码解析:利用随机数分别取0到99的数字,然后做加减乘(为啥没除法?懒!因为还得算整除。),背景干扰什么的之前写过,此处不赘述。如果说你想考验下用户什么的,可以自己整个难度高一点的公式,比如:1+2*3之类的,反正直接让datatable去计算结果就行。。