#region 验证码
public FileResult CreateCode()
{
return File(CreateCodeImg(), "image/jpeg");
}
public byte[] CreateCodeImg()
{
//字体颜色
Color[] color = { Color.Red, Color.Black, Color.Blue, Color.Green };
//字体类型
string[] font = { "黑体", "隶书", "幼圆" };
//创建图片对象
Bitmap image = new Bitmap(120, 50);
//创建画板
Graphics g = Graphics.FromImage(image);
//使用白色清空画板
g.Clear(Color.White);
try
{
//创建随机生成器
Random random = new Random();
//绘制线
for (int i = 0; i < 3; i++)
{
int x1 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int x2 = random.Next(image.Width);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(color[random.Next(color.Length)]), x1, y1, x2, y2);
}
//绘制干扰点
for (int i = 0; i < 20; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, color[random.Next(color.Length)]);
}
string validateCode = Guid.NewGuid().ToString().Replace("-", "").Substring(2, 4);
TempData["code"] = validateCode;
//绘制字符
for (int i = 0; i < validateCode.Length; i++)
{
g.DrawString(validateCode[i].ToString(),
new Font(font[random.Next(font.Length)], 20),
new SolidBrush(color[random.Next(color.Length)]),
i * 20, 5);
}
//绘制边框
g.DrawRectangle(new Pen(Color.Gray), -1, -1, image.Width + 1, image.Height + 1);
//保存图片
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Jpeg);
return ms.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}
#endregion