asp.net|web|驗證碼 最近,工作中接到一項任務,開發一個頁面驗證碼功能,查閱了一些網上的資料,並結合以前的繪圖方面的知識,實現了如下的解決方案。產生的驗證碼效果如圖:
要解決的問題:
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);
// 3. 繪製幹擾線條,採用比背景略深一些的顏色
int nLines = 3;
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 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// 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("Courier New",
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+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;
}
[1] [2] 下一頁