/// <summary>
/// 绘制验证码的方法
/// </summary>
void SetCode()
{
//默认验证码
string code = "2wa4";
code = code.Trim();
if (String.IsNullOrEmpty(code))
{
return;
}
//验证码大小宽65,高20
Bitmap image = new Bitmap(65, 20);
//创建绘图对象Graphics
Graphics graphics = Graphics.FromImage(image);
//随机
Random r = new Random();
graphics.Clear(Color.White);
//绘制四条随机出现的线
for (int i = 0; i < 4; i++)
{
int x1 = r.Next(image.Width);
int y1 = r.Next(image.Height);
int x2 = r.Next(image.Width);
int y2 = r.Next(image.Height);
graphics.DrawLine(new Pen(Brushes.Black, 1), new Point(x1, y1), new Point(x2, y2));
}
this.BackgroundImage = image;
this.BackgroundImageLayout = ImageLayout.Center;
graphics.DrawRectangle(new Pen(Brushes.Black), 0, 0, image.Width - 1, image.Height - 1);
graphics.DrawString(code, new Font("微软雅黑", 12, FontStyle.Bold), Brushes.Red, 8, -2);
}
绘制随机出现数字加字幕的验证码
Random r = new Random();
/// <summary>
/// 随机出现验证码
/// </summary>
/// <param name="code">传递验证码个数</param>
/// <returns>返回验证码</returns>
private string MakeCode(int code)
{
int number;
StringBuilder CheckCode = new StringBuilder();
for (int i = 0; i < code; i++)
{
number = r.Next();
///判断出现数字
if (number % 2 == 0)
{
CheckCode.Append((char)('0' +(number % 10)));
}
///判断出现英文字母
else
{
CheckCode.Append((char)('A' +(number % 26)));
}
}
return CheckCode.ToString();
}
/// <summary>
/// 绘制验证码
/// </summary>
void SetCodeImage()
{
string code = MakeCode(4);
if (String.IsNullOrEmpty(code))
{
return;
}
Bitmap image = new Bitmap((int)Math.Ceiling(code.Length * 20.0), 20);
Graphics graphics = Graphics.FromImage(image);
graphics.Clear(Color.White);
for (int i = 0; i < 4; i++)
{
int x1 = r.Next(image.Width);
int y1 = r.Next(image.Height);
int x2 = r.Next(image.Width);
int y2 = r.Next(image.Height);
graphics.DrawLine(new Pen(Color.Black, 2), new Point(x1, y1), new Point(x2, y2));
}
graphics.DrawString(code, new Font("黑体", 18, FontStyle.Bold), Brushes.Red,8,-2);
this.BackgroundImage = image;
this.BackgroundImageLayout = ImageLayout.Center;
graphics.DrawRectangle(new Pen(Color.Black), 0, 0, image.Width-1, image.Height-1);
}