Service1.asmx
using System.Drawing;
[WebMethod]
public byte[] GenerateImage(int nLen,ref string strKey){
int nBmpWidth=13*nLen+5;
int nBmpHeight=25;
System.Drawing.Bitmap bmp=new System.Drawing.Bitmap (nBmpWidth,nBmpHeight);
//1.生成随机图像背景颜色
int nRed,nGreen,nBlue;
System.Random rd=new Random((int)System.DateTime.Now.Ticks);
nRed=rd.Next(255)%128+128;
nGreen=rd.Next(255)%128+128;
nBlue=rd.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=10;
System.Drawing.Pen pen=new System.Drawing.Pen(System.Drawing.Color.FromArgb(nRed-17,nGreen-17,nBlue-17),2);
for(int a=0;a<nLines;a++){
int x1=rd.Next()%nBmpWidth;
int y1=rd.Next()%nBmpHeight;
int x2=rd.Next()%nBmpWidth;
int y2=rd.Next()%nBmpHeight;
graph.DrawLine(pen,x1,y1,x2,y2);
}
//采用的字符集,可以随意拓展
string strCode="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
//4.循环获得字符,并绘制
string strResult="";
for(int i=0;i<nLen;i++){
int x=(i*13+rd.Next(3));
int y=rd.Next(4)+1;
//确定字体
System.Drawing.Font font=new System.Drawing.Font ("arial",12+rd.Next()%4,System.Drawing.FontStyle.Bold);
char c=strCode[rd.Next(strCode.Length)];//随机获取字符
strResult +=c.ToString();
//绘制字符
graph.DrawString(c.ToString(),font,new SolidBrush(System.Drawing.Color.FromArgb(nRed-60,nGreen-60+y*3,nBlue-40+y*3)),x,y);
}
//图画片的前景噪音点
for(int i=0;i<10;i++){
int x=rd.Next(bmp.Width);
int y=rd.Next(bmp.Height);
bmp.SetPixel(x,y,Color.FromArgb(rd.Next()));
}
//图画片的边框线
graph.DrawRectangle(new Pen(Color.Silver),0,0,bmp.Width-1,bmp.Height-1);
//输出
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;
}
gif.aspx
private void Page_Load(object sender, System.EventArgs e)
{
GenerateImage.Service1 imgsvr=new WebImage.GenerateImage.Service1();
string strKey = "";
byte[] data = imgsvr.GenerateImage(6,ref strKey);
Session["regcode"] = strKey;
Response.OutputStream.Write(data,0,data.Length);
}
Main.aspx
private void btLogin_Click(object sender, System.EventArgs e)
{
if(this.tbCode.Text!=Session["regcode"].ToString())
Response.Write("注册码错误!");
}