ASP.NET 生成随机验证码

我一直觉得用第三方控件生成的验证码太花了,用户体验不好,有的很难看清楚到底是什么,还是那种比较清楚一点的给人的感觉好点。

/// <summary>

/// 这个方法用来生成随机验证码

/// </summary>

private void ShowCode()

{

Random ran = new Random();

int intRandom = ran.Next(10001, 99999);

//将随机数写入Session

Session.RemoveAll();

Session["RandCode"] = intRandom;

//字体名

string strFontName = "Arial";

//字体大小

int intFontSize = 9;

//图像宽

int intWidth = 50;

//图像长

int intHeight = 18;

//背景颜色

Color bgColor = ColorTranslator.FromHtml("#EFF3FF");

//前景色

Color foreColor = ColorTranslator.FromHtml("#00ff00");

//字体

Font forFont = new Font(strFontName, intFontSize, FontStyle.Bold);

//生成图片

Bitmap newBitmap = new Bitmap(intWidth, intHeight, PixelFormat.Format32bppArgb);

Graphics g = Graphics.FromImage(newBitmap);

//定义一个四方形框与字片一样大小

Rectangle newRect = new Rectangle(0, 0, intWidth, intHeight);

//背景色

g.FillRectangle(new SolidBrush(bgColor), newRect);

//写字

g.DrawString(intRandom.ToString(), forFont, new SolidBrush(foreColor), 2, 2);

MemoryStream mStream = new MemoryStream();

//存入MemoryStream

newBitmap.Save(mStream, ImageFormat.Gif);

g.Dispose();

newBitmap.Dispose();

//发送

//Response.ClearContent();

Response.ContentType = "image/GIF";

FileStream fis = new FileStream(MapPath("images/") + "yanzheng.gif", FileMode.Create);

fis.Write(mStream.ToArray(), 0, mStream.ToArray().Length);

fis.Close();

this.Image1.ImageUrl = "images/yanzheng.gif";

//Response.End();

}

在项目里面指定一个文件夹命名为images,这样就OK了。