[C#] 纯文本查看 复制代码
/// <summary>
/// 生成验证码
/// </summary>
private void CreateCode()
{
HttpResponse resp = this.Page.Response;
//用来存取验证码
String chkCode = string.Empty;
//颜色列表
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.DarkBlue };
//字体列表
String[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" };
Random rnd = new Random();
//阿拉伯数字
int[] num1 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//汉字数字
Char[] num2 = { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' };
//汉字数字2
Char[] num3 = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };
int[] suiJi = { 1, 2, 3 };
int nn = suiJi[rnd.Next(suiJi.Length)];
if (nn == 1)
{
int i3 = rnd.Next(num3.Length);
Char c3 = num3[i3];
int i2 = rnd.Next(num2.Length);
Char c2 = num2[i2];
Number1 = i3;
Number2 = i2;
Result = Number1 + Number2;
chkCode = c3 + "+" + c2 + "=" + "?";
}
if (nn == 2)
{
int i3 = rnd.Next(num3.Length);
Char c3 = num3[i3];
int i2 = rnd.Next(num2.Length);
Char c2 = num2[i2];
Number1 = i3;
Number2 = i2;
if (Number1 < Number2)
{
this.CreateCode();
}
Result = Number1 - Number2;
chkCode = "?" + "+" + c2 + "=" + c3;
}
if (nn == 3)
{
int i3 = rnd.Next(num3.Length);
Char c3 = num3[i3];
int i2 = rnd.Next(num2.Length);
Char c2 = num2[i2];
Number1 = i3;
Number2 = i2;
if (Number1 > Number2)
{
this.CreateCode();
}
Result = Number2 - Number1;
chkCode = c3 + "+" + "?" + "=" + c2;
}
//保存验证码到Session对象
this.Page.Session["Code"] = Result;
//创建一个位图
Bitmap bmp = new Bitmap(200, 30);
//绘制涂层
Graphics g = Graphics.FromImage(bmp);
//填充背景色为白色
//画噪线
for (int i = 0; i < 6; i++)
{
int x1 = rnd.Next(100);
int y1 = rnd.Next(30);
int x2 = rnd.Next(100);
int y2 = rnd.Next(30);
Color clr = color[rnd.Next(color.Length)];
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
}
//画噪点
for (int i = 0; i < 100; i++)
{
int x = rnd.Next(bmp.Width);
int y = rnd.Next(bmp.Height);
Color clr = color[rnd.Next(color.Length)];
bmp.SetPixel(x, y, clr);
}
//画验证码
for (int i = 0; i < chkCode.Length; i++)
{
String fnt = font[rnd.Next(font.Length)];
Font ft = new Font(fnt, 16);
Color clr = color[rnd.Next(color.Length)];
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 20, (float)6);
}
//将验证码写入内存流
MemoryStream ms = new MemoryStream();
try
{
bmp.Save(ms, ImageFormat.Png);
resp.ClearContent();
resp.ContentType = "image/Png";
resp.BinaryWrite(ms.ToArray());
resp.Flush();
resp.End();
}
finally
{
bmp.Dispose();
g.Dispose();
}
}