c#_生成图片式验证码

废话不多说直接上代码。

     class Check_Code
{
/// <summary>
/// 生成随机验证码数字+字母
/// </summary>
/// <param name="codelen">验证码长度</param>
/// <returns>返回验证码</returns>
public static string MakeCode(int codelen)
{
if (codelen < )
{
return string.Empty;
}
int number;
StringBuilder strCheckCode = new StringBuilder();
Random random = new Random();
for (int index = ; index < codelen; index++)
{
number = random.Next();
if (number % == )
{
strCheckCode.Append((char)('' + (char)(number % )));//生成随机数字
}
else
{
strCheckCode.Append((char)('A' + (char)(number % )));//生成随机字母
}
}
return strCheckCode.ToString();
}
public static MemoryStream CheckCodeImage(string CheckCode)
{
if (string.IsNullOrEmpty(CheckCode))
{
return null;
}
Bitmap image = new Bitmap((int)Math.Ceiling((CheckCode.Length * 12.5)), );
Graphics graphic = Graphics.FromImage(image);//创建一个验证码图片
try
{
Random random = new Random();
graphic.Clear(Color.White);
int x1 = , y1 = , x2 = , y2 = ;
for (int index = ; index < ; index++)
{
x1 = random.Next(image.Width);
x2 = random.Next(image.Width);
y1 = random.Next(image.Height);
y2 = random.Next(image.Height);
graphic.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", , (FontStyle.Bold | FontStyle.Italic));//Font设置字体,字号,字形
//设置图形渐变色的起始颜色与终止颜色,渐变角度
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(, , image.Width, image.Height), Color.Red, Color.DarkRed, 1.2f, true);
graphic.DrawString(CheckCode, font, brush, , );
int X = ; int Y = ;
//绘制图片的前景噪点
for (int i = ; i < ; i++)
{
X = random.Next(image.Width);
Y = random.Next(image.Height);
image.SetPixel(X, Y, Color.FromArgb(random.Next()));
}
//画图片的边框线
graphic.DrawRectangle(new Pen(Color.Silver), , , image.Width - , image.Height - );
//将图片保存为stream流返回
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms;
}
finally
{
graphic.Dispose();
image.Dispose();
}
}
}

生成验证码图片,需要先生成验证码,再将验证码处理为图片。

转载引用黎木博客-https://www.cnblogs.com/running-mydream/p/4071528.html

上一篇:洛谷P1962 斐波那契数列 || P1349 广义斐波那契数列[矩阵乘法]


下一篇:C#一些小技巧