image.aspx.cs
protected void Page_Load(object sender, EventArgs e) { string tmp = RndNum(4); HttpCookie a = new HttpCookie("ImageV", tmp); Response.Cookies.Add(a); this.ValidateCode(tmp); } private int _unitWith = 25; private int _unitHeight = 25; private void ValidateCode(string vNum) { Bitmap img = null; Graphics g = null; MemoryStream ms = null; int gheight = vNum.Length * _unitWith; img = new Bitmap(gheight, _unitHeight); g = Graphics.FromImage(img); //背景颜色 g.Clear(Color.White); //文字字体 Font f = new Font("Wide Latin", 12); //文字颜色 SolidBrush s = new SolidBrush(Color.Black); //定义钢笔,用于绘制干扰线 Pen pen1 = new Pen(Color.FromArgb(255, 100, 100), 1); Pen pen2 = new Pen(Color.FromArgb(255, 100, 100), 0); //定义一个随机数对象,用于绘制干扰线 Random rand = new Random(); //生成两条横向的干扰线 for (int i = 0; i < 3; i++) { //定义起点 Point p1 = new Point(0, rand.Next(img.Height)); //定义终点 Point p2 = new Point(img.Width, rand.Next(img.Height)); //绘制直线 g.DrawLine(pen1, p1, p2); } //生成两条纵向的干扰线 for (int i = 0; i < 3; i++) { //定义起点 Point p1 = new Point(rand.Next(img.Width), 0); //定义终点 Point p2 = new Point(rand.Next(img.Width), img.Height); //绘制直线 g.DrawLine(pen2, p1, p2); } g.DrawString(vNum, f, s, 3, 3); ms = new MemoryStream(); img.Save(ms, ImageFormat.Jpeg); Response.ClearContent(); Response.ContentType = "image/Jpeg"; Response.BinaryWrite(ms.ToArray()); g.Dispose(); img.Dispose(); Response.End(); } private string RndNum(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,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; string[] vcArray = vchar.Split(new Char[] { ',' }); 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(61); if (temp != -1 && temp == t) { return RndNum(vcodeNum); } temp = t; vNum += vcArray[t]; } return vNum; }
使用:<asp:ImageButton ID="ImageButton1" runat="server" Height="35px" Width="121px" />
ImageButton1.ImageUrl = "image.aspx";