/// <summary>
/// 数值验证码
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button1_Click(object sender, EventArgs e)
{
string sourcecode = "0123456789";
string code = "";
Random random = new Random();
for (int i = 0; i < 6; i++)
{
int flag = random.Next(0, 9);
code += sourcecode.Substring(flag, 1);
}
label1.Text = code;
}
/// <summary>
/// 数值+字母验证码
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button2_Click(object sender, EventArgs e)
{
string sourcecode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string code = "";
//随机获取
Random random = new Random();
for (int i = 0; i < 6; i++)
{
int flag = random.Next(0, 61);
code += sourcecode.Substring(flag, 1);
}
label2.Text = code;
}
/// <summary>
/// 图片验证码
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button3_Click(object sender, EventArgs e)
{
string sourcecode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string code = "";
//随机获取
Random random = new Random();
for (int i = 0; i < 6; i++)
{
int flag = random.Next(0, 61);
code += sourcecode.Substring(flag, 1);
}
//定义一个画板
Bitmap bitmap = new Bitmap(160, 50);//设置的是宽高
//定义画布
Graphics graphics = Graphics.FromImage(bitmap);
//在画布上设置背景颜色
graphics.FillRectangle(new SolidBrush(Color.Red), 0, 0, 160, 50);
//设置字体
Font font = new Font(new FontFamily("微软雅黑"), 15.0f);
//画干扰线
for (int i = 0; i < 6; i++)
{
Pen pen = new Pen(new SolidBrush(Color.Yellow), 1);
Point point = new Point(random.Next(0, 160), random.Next(2, 80));
Point point1 = new Point(random.Next(0, 160), random.Next(2, 90));
graphics.DrawLine(pen, point, point1);
}
//画图
graphics.DrawString(code, font, new SolidBrush(Color.Green), new PointF(10, 10));
//保存图片
using (FileStream stream = new FileStream(@"C:\Users\张艳薇\Desktop\needyou\code.png", FileMode.Create, FileAccess.ReadWrite))
{
bitmap.Save(stream, ImageFormat.Png);
}
}