参考这篇文章: http://www.cnblogs.com/yuangang/p/6000460.html
using System;
using System.IO;
using System.DrawingCore;
using System.DrawingCore.Imaging; namespace MobileWeb.Utility
{
public class Captcha
{ public string CreateValidateNumber(int length)
{
int[] randMembers = new int[length];
int[] validateNums = new int[length];
System.Text.StringBuilder validateNumberStr = new System.Text.StringBuilder();
//生成起始序列值
int seekSeek = unchecked((int)DateTime.Now.Ticks);
Random seekRand = new Random(seekSeek);
int beginSeek = (int)seekRand.Next(, Int32.MaxValue - length * );
int[] seeks = new int[length];
for (int i = ; i < length; i++)
{
beginSeek += ;
seeks[i] = beginSeek;
}
//生成随机数字
for (int i = ; i < length; i++)
{
Random rand = new Random(seeks[i]);
int pownum = * (int)Math.Pow(, length);
randMembers[i] = rand.Next(pownum, Int32.MaxValue);
}
//抽取随机数字
for (int i = ; i < length; i++)
{
string numStr = randMembers[i].ToString();
int numLength = numStr.Length;
Random rand = new Random();
int numPosition = rand.Next(, numLength - );
validateNums[i] = Int32.Parse(numStr.Substring(numPosition, ));
}
//生成验证码
for (int i = ; i < length; i++)
{
validateNumberStr.Append(validateNums[i].ToString());
}
return validateNumberStr.ToString();
} public byte[] CreateValidateGraphic(string validateNum)
{
Bitmap Img = null;
Graphics g = null;
MemoryStream ms = null;
Random random = new Random();
//验证码颜色集合
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple }; //验证码字体集合
string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }; //定义图像的大小,生成图像的实例
Img = new Bitmap((int)validateNum.Length * , ); g = Graphics.FromImage(Img);//从Img对象生成新的Graphics对象 g.Clear(Color.White);//背景设为白色 //在随机位置画背景点
for (int i = ; i < ; i++)
{
int x = random.Next(Img.Width);
int y = random.Next(Img.Height);
g.DrawRectangle(new Pen(Color.LightGray, ), x, y, , );
}
//验证码绘制在g中
for (int i = ; i < validateNum.Length; i++)
{
int cindex = random.Next();//随机颜色索引值
int findex = random.Next();//随机字体索引值
Font f = new Font(fonts[findex], , FontStyle.Bold);//字体
Brush b = new SolidBrush(c[cindex]);//颜色
int ii = ;
if ((i + ) % == )//控制验证码不在同一高度
{
ii = ;
}
g.DrawString(validateNum.Substring(i, ), f, b, + (i * ), ii);//绘制一个验证字符
}
ms = new MemoryStream();//生成内存流对象
Img.Save(ms, ImageFormat.Jpeg);//将此图像以Png图像文件的格式保存到流中 //回收资源
g.Dispose();
Img.Dispose();
return ms.ToArray();
}
} }
调用方法, Controller加一个方法, HTML里 <img id="cc_image" src="/product/ValidateCode" alt="点击切换验证码">
public ActionResult ValidateCode()
{
Captcha captcha = new Captcha(); var code = captcha.CreateValidateNumber();
HttpContext.Session.SetString("ValidateCode", code);
return File(captcha.CreateValidateGraphic(code), "image/jpeg");
}