public void ProcessRequest(HttpContext context) { //0.0得到字符串 string vcode = GetVcode(4); //0.1将验证码保存到Session中 //context.Session[Kit.vcode]=vcode; context.Session[Kit.vcode] = vcode; //1.0准备一个画板 using (Image img=new Bitmap(60,20)) { //2.0准备一个画家对象 using (Graphics g=Graphics.FromImage(img)) { //将验证码的背景色变成白色 g.Clear(Color.White); //画边框 g.DrawRectangle(Pens.Black, 0, 0, img.Width - 1, img.Height - 1); //画一些干扰点 DrawPoint(g,img,50); //将验证码画到图片上 g.DrawString(vcode,new Font("宋体",16,FontStyle.Bold),Brushes.Red,0,0); DrawPoint(g, img, 50); } //将图片保存到输出流 img.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg); } } /// <summary> /// 画干扰点 /// </summary> /// <param name="g"></param> /// <param name="img"></param> /// <param name="p"></param> private void DrawPoint(Graphics g, Image img, int p) { //得到x,y坐标 int x; int y; //得到点 Point p1; Point p2; for (int i = 0; i < p; i++) { x = r.Next(0,img.Width); y = r.Next(0,img.Height); //根据xy生成点 p1 = new Point(x,y); p2 = new Point(x+1,y+1); //连接两点 g.DrawLine(Pens.Black,p1,p2); } } Random r = new Random(); /// <summary> /// 得到字符串 /// </summary> /// <param name="p"></param> /// <returns></returns> private string GetVcode(int p) { string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,O,P,Q,R,S,T,U,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,m,n,o,p,q,s,t,u,w,x,y,z"; //切割字符串 string[] array = allChar.Split(new char[] { ‘,‘ }, StringSplitOptions.RemoveEmptyEntries); //创建验证码字符串 string vcode = string.Empty; for (int i = 0; i < p; i++) { int index = r.Next(0,array.Length); vcode += array[index]; } return vcode; }
时间: 2024-10-06 22:34:23