/// 产生随机的混合编码-使用文字,字母,数字混合
/// </summary>
/// <param name="mixLength"></param>
/// <returns></returns>
private string GetRndMix(int mixLength)
{
String Vchar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z,好,哈,弹,平,合,下,天,人,无,有,中,木,不,字";
String[] VcArray = Vchar.Split(',');
String VMix = "";
Random random = new Random();
for (int i = 1; i <= mixLength; i++)
{
int iNum = 0;
iNum = random.Next(VcArray.Length);
VMix += VcArray[iNum];
}
return VMix;
}
/// <summary>
/// 根据产生的随机数生成图象
/// </summary>
/// <param name="strCode"></param>
private void CreateImg(string strCode, HttpContext context)
{
//也可以不用指定的图片,而是画一个背景图片
Bitmap bitMapImage = new Bitmap(100, 25);
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.FillRectangle(new SolidBrush(Color.White), 0, 0, 100, 25);
//设置画笔的输出模式
graphicImage.SmoothingMode = SmoothingMode.HighSpeed;
//添加文本字符串
graphicImage.DrawString(strCode, new Font("Arial", 15, FontStyle.Bold), SystemBrushes.WindowText, new Point(0, 0));
//画图片的前景噪音点
Random randomPixel = new Random();
for (int i = 0; i < 200; i++)
{
int x = randomPixel.Next(bitMapImage.Width);
int y = randomPixel.Next(bitMapImage.Height);
bitMapImage.SetPixel(x, y, Color.FromArgb(randomPixel.Next(0, 255), randomPixel.Next(0, 255), randomPixel.Next(0, 255)));
}
//设置图像输出的格式
context.Response.ContentType = "image/jpeg";
//保存数据流
bitMapImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);
//释放占用的资源
graphicImage.Dispose();
bitMapImage.Dispose();
}
生成中文验证码也可以,根据汉字编码来生成,这里就不发了,本文是自定义的一些简单的文字