開發基於ASP.NET WebService的圖片驗證碼服務

來源:互聯網
上載者:User

最近,工作中接到一項任務,開發一個頁面驗證碼功能,查閱了一些網上的資料,並結合以前的繪圖方面的知識,實現了如下的解決方案。產生的驗證碼效果如圖:

要解決的問題:

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);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.