最近,工作中接到一項任務,開發一個頁面驗證碼功能,查閱了一些網上的資料,並結合以前的繪圖方面的知識,實現了如下的解決方案。產生的驗證碼效果如圖:
要解決的問題:
1. 如何隨機產生圖片
產生System.Drawing.Bitmap對象,使用System.Drawing.Graphics向位元影像對象中繪圖。
2. 如何在WebService的方法中通過參數傳遞圖片資料
將Bitmap對象輸出成位元組流,WebMothod使用位元組數組返回該位元組流。
執行個體:
1. 用VS.NET 2003建立一個ASP.NET Webservice工程,預設的Service名為MyService,為MyService添加一個名為GenerateVerifyImage的WebMethod。該方法的代碼如下:
/// <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. 產生隨機背景顏色
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);