急用。
[CODE]using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
namespace LXZHBlog
{
/// <summary>
/// 验证码生成页面
/// </summary>
public class VerifyCode : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
string vnum;
vnum=GetByRndNum(6);
Page.Session.Add("VerifyCode",vnum);
Page.Session.Add("RegistCode",vnum);
Response.ClearContent(); //需要输出图象信息 要修改HTTP头
Response.ContentType="image/jpg";
Response.BinaryWrite(GetByValidateCode(vnum).ToArray());
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
public MemoryStream GetByValidateCode(string VNum)//返回内存流
{
Bitmap Img = null;
Graphics g = null ;
MemoryStream ms = null ;
Random random = new Random();
int gheight = VNum.Length*12;
Img = new Bitmap(gheight,24);
g = Graphics.FromImage(Img);
Font f = new Font("Arial", 12, FontStyle.Bold);
g.Clear (GetByRandColor(204,255) );//设定背景色
Pen blackPen = new Pen(Color.Ivory ,3);
for (int i=0;i<155;i++)// 随机产生干扰线,使图象中的认证码不易被其它程序探测到
{
int x = random.Next (gheight);
int y = random.Next (20);
int xl = random.Next (6);
int yl = random.Next (2);
g.DrawLine (blackPen,x,y,x+xl,y+yl);
}
SolidBrush s = new SolidBrush(Color.SandyBrown);
g.DrawString(VNum,f,s,3,3);
ms=new MemoryStream();
Img.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
g.Dispose();
Img.Dispose();
return ms;
}
Color GetByRandColor(int fc,int bc)
{
Random random = new Random();
if(fc>255) fc=255;
if(bc>255) bc=255;
//if(ac>255) ac=255;
int r=fc+random.Next (bc-fc);
int g=fc+random.Next (bc-fc);
int b=fc+random.Next (bc-bc);
Color rs = Color.FromArgb (r,g,b);
return rs;
}
private string GetByRndNum(int VcodeNum)
{
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 VNum = "" ;
int temp = -1 ;//记录上次随机数值,尽量避免生产几个一样的随机数
//采用一个简单的算法以保证生成随机数的不同
Random rand =new Random();
for ( int i = 1 ; i < VcodeNum+1 ; i++ )
{
if ( temp != -1)
{
rand =new Random(i*temp*unchecked((int)DateTime.Now.Ticks));
}
int t = rand.Next(35) ;
if (temp != -1 && temp == t)
{
return GetByRndNum( VcodeNum );
}
temp = t ;
VNum += VcArray[t];
}
return VNum ;
}
}
}[/CODE]