生成随机验证码帮助类
public class VerifyCode
{
/// <summary>
/// 生成验证码
/// </summary>
/// <returns></returns>
public byte[] GetVerifyCode()
{
int num = 80;
int num2 = 30;
int num3 = 16;
string text = string.Empty;
Color[] array = new Color[]
{
Color.Black,
Color.Red,
Color.Blue,
Color.Green,
Color.Orange,
Color.Brown,
Color.Brown,
Color.DarkBlue
};
string[] array2 = new string[]
{
"Times New Roman"
};
char[] array3 = new char[]
{
'2',
'3',
'4',
'5',
'6',
'8',
'9',
'a',
'b',
'd',
'e',
'f',
'h',
'k',
'm',
'n',
'r',
'x',
'y',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'J',
'K',
'L',
'M',
'N',
'P',
'R',
'S',
'T',
'W',
'X',
'Y'
};
Random random = new Random();
for (int i = 0; i < 4; i++)
{
text += array3[random.Next(array3.Length)].ToString();
}
WriteSession("session_verifycode", Md5Helper.MD5(text.ToLower(), 16));
Bitmap bitmap = new Bitmap(num, num2);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.Clear(Color.White);
for (int j = 0; j < 1; j++)
{
int x = random.Next(num);
int y = random.Next(num2);
int x2 = random.Next(num);
int y2 = random.Next(num2);
Color color = array[random.Next(array.Length)];
graphics.DrawLine(new Pen(color), x, y, x2, y2);
}
for (int k = 0; k < text.Length; k++)
{
string familyName = array2[random.Next(array2.Length)];
Font font = new Font(familyName, (float)num3);
Color color2 = array[random.Next(array.Length)];
graphics.DrawString(text[k].ToString(), font, new SolidBrush(color2), (float)k * 18f, 0f);
}
MemoryStream memoryStream = new MemoryStream();
byte[] result;
try
{
bitmap.Save(memoryStream, ImageFormat.Png);
result = memoryStream.ToArray();
}
catch (Exception)
{
result = null;
}
finally
{
graphics.Dispose();
bitmap.Dispose();
}
return result;
}
/// <summary>
/// 写Session
/// </summary>
/// <param name="key">Session的键名</param>
/// <param name="value">Session的键值</param>
public void WriteSession(string key, string value)
{
WriteSession<string>(key, value);
}
/// <summary>
/// 写Session
/// </summary>
/// <typeparam name="T">Session键值的类型</typeparam>
/// <param name="key">Session的键名</param>
/// <param name="value">Session的键值</param>
public void WriteSession<T>(string key, T value)
{
bool flag = string.IsNullOrWhiteSpace(key);
if (!flag)
{
HttpContext.Current.Session[key] = value;
}
}
}
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16522530.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。