Recently, work received a task, the development of a page verification code function, access to some information on the web, and combined with the previous knowledge of the drawing, to achieve the following solutions. The generated verification code effect is shown in figure:
Issues to resolve:
1. How to generate pictures randomly
Generates the System.Drawing.Bitmap object and uses System.Drawing.Graphics to draw to the bitmap object.
2. How to pass the picture data through the parameter in the WebService method
The bitmap object is exported as a byte stream, and Webmothod is returned by using an array of bytes.
Instance:
1. Create a ASP.net WebService project with Vs.net 2003, the default service name is MyService, and add a myservice named Generateverifyimage to WebMethod. The code for the method is as follows:
/// <summary>
/// 生成图片验证码
/// </summary>
/// <param name="nLen">验证码的长度</param>
/// <param name="strKey">输出参数,验证码的内容</param>
/// <returns>图片字节流</returns>
[WebMethod]
public byte[] GenerateVerifyImage(int nLen,ref string strKey)
{
int nBmpWidth = 13*nLen+5;
int nBmpHeight = 25;
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(nBmpWidth,nBmpHeight);
1. Generate Random background color
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. Fill a bitmap background
System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);
graph.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(nRed,nGreen,nBlue))
,0
,0
,nBmpWidth
,nBmpHeight);