asp.net創(chuàng)建位圖生成驗證圖片類(驗證碼類)
代碼:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
//創(chuàng)建位圖,并且給指定邊框的寬高
using (Image img=new Bitmap(80,25))
{
//創(chuàng)建畫家對象,在img對象畫字符串
using (Graphics g=Graphics.FromImage(img))
{
//設(shè)置位圖的背景顏色,默認(rèn)是黑色
g.Clear(Color.White);
//設(shè)置驗證碼的寬高, img.Width-1, img.Height-1主要是背景顏色覆蓋了邊框線
g.DrawRectangle(Pens.Black, 0, 0, img.Width-1, img.Height-1);
//傳100個噪點,傳畫家對象,位圖對象
DrawPoint(100, g, img);
//畫4個驗證碼的字符串
string vcode=GetCode(4);//vcode這里可以賦值給Cookie
g.DrawString(vcode,
new Font("Arial", 14, FontStyle.Strikeout | FontStyle.Strikeout), // FontStyle字體的樣式,多個樣式,需要|線
Brushes.Black,
new RectangleF(r.Next(20), r.Next(7), img.Width, img.Height));
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//保存驗證碼對象,指定是Jpeg格式
}
}
}
//畫噪點方法
void DrawPoint(int point,Graphics g,Image img)
{
for (int i = 0; i < point; i++)
{
int x = r.Next(img.Width);
int y = r.Next(img.Width);
g.DrawLine(Pens.Red,
new Point(x, y),
new Point(x+2, y+2));
}
}
//隨機數(shù)
Random r = new Random();
//畫字符創(chuàng)
string GetCode(int point)
{
string txtStr = "ASF2345WE5R9F3HMBCZ455K";//這里的string字符串將會轉(zhuǎn)成 char數(shù)組,阿拉伯?dāng)?shù)字1和小寫字母l最好別寫在里面,會搞胡亂。
char[] charArr = txtStr.ToArray();
int num = 0;
string code = "";
for (int i = 0; i <point; i++)
{
num = r.Next(charArr.Length);
code +=charArr[num];
}
return code;
}
相關(guān)文章
ASP.NET Core使用GraphQL第一章之Hello World
這篇文章主要給大家介紹了關(guān)于ASP.NET Core使用GraphQL第一章之Hello World的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11IIS故障(Connections_Refused)問題分析及處理
這幾天某地市Web服務(wù)器連續(xù)多次出現(xiàn)故障問題(Connections_Refused),正好借這個案例向大家詳細介紹下,需要了解的朋友可以參考下2012-12-12