/**////<summary> /// 生成图片验证码 ///</summary> ///<param name="nlen">验证码的长度</param> ///<param name="strkey">输出参数,验证的内容</param> ///<returns>图片字节流</returns> [WebMethod] publicbyte[] generateverifyimage(int nlen,refstring strkey) ...{ int nbmpwidth =13*nlen+5; int nbmpheight=25; System.Drawing.Bitmap bmp =new Bitmap(nbmpwidth,nbmpheight); //1.生成随机背景颜色 int nred,ngreen,nblue;//背景的r,g,b三元色 System.Random rdm =new Random((int)System.DateTime.Now.Ticks); nred = rdm.Next(255)%128+128; ngreen = rdm.Next(255)%128+128; nblue = rdm.Next(255)%128+128; //2.填充位图背景 System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp); graph.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(nred,ngreen,nblue)),0,0,nbmpwidth,nbmpheight); //3.绘制干扰线条,采用比背景略深一些的颜色 int nlines =3; System.Drawing.Pen pen =new Pen(System.Drawing.Color.FromArgb(nred-17,ngreen-17,nblue-17),2); for(int a=0;a<nlines;a++) ...{ int x1=rdm.Next() % nbmpwidth; int y1=rdm.Next() % nbmpheight; int x2=rdm.Next() % nbmpwidth; int y2=rdm.Next() % nbmpheight; graph.DrawLine(pen,x1,y1,x2,y2); } //采用的字符集,可以随即拓展,并可以控制字符出现的几率 string strcode ="abcdefghijklmnopqrstuvwxyz"; //4.循环取得字符,并绘制 string strresult =""; for(int i=0;i<nlen;i++) ...{ int x = (i*13+ rdm.Next(3)); int y = rdm.Next(4) +1; //确定字体 System.Drawing.Font font =new Font("courer new",12+rdm.Next()%4,System.Drawing.FontStyle.Bold); char c = strcode[rdm.Next(strcode.Length)];//随机获取字符 strresult += c.ToString(); //绘制字符 graph.DrawString(c.ToString(),font,new SolidBrush(System.Drawing.Color.FromArgb(nred-60+y*3,ngreen-60+y*3,nblue-40+y*3)),x,y); } //5.输出字符流 System.IO.MemoryStream bstream =new System.IO.MemoryStream(); bmp.Save(bstream,System.Drawing.Imaging.ImageFormat.Jpeg); bmp.Dispose(); graph.Dispose(); strkey = strresult; byte[] bytereturn = bstream.ToArray(); bstream.Close(); return bytereturn; }
建立WEBFORM页面:
在C#代码中添加一下这个webservice引用
在Page_Load中添加测试代码
myservice.Service1 s = new Service1(); string strkey = ""; byte[] data = s.generateverifyimage(5,ref strkey); Response.OutputStream.Write(data,0,data.Length);