public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
//創(chuàng)建位圖,并且給指定邊框的寬高
using (Image img=new Bitmap(80,25))
{
//創(chuàng)建畫(huà)家對(duì)象,在img對(duì)象畫(huà)字符串
using (Graphics g=Graphics.FromImage(img))
{
//設(shè)置位圖的背景顏色,默認(rèn)是黑色
g.Clear(Color.White);
//設(shè)置驗(yàn)證碼的寬高, img.Width-1, img.Height-1主要是背景顏色覆蓋了邊框線(xiàn)
g.DrawRectangle(Pens.Black, 0, 0, img.Width-1, img.Height-1);
//傳100個(gè)噪點(diǎn),傳畫(huà)家對(duì)象,位圖對(duì)象
DrawPoint(100, g, img);
//畫(huà)4個(gè)驗(yàn)證碼的字符串
string vcode=GetCode(4);//vcode這里可以賦值給Cookie
g.DrawString(vcode,
new Font("Arial", 14, FontStyle.Strikeout | FontStyle.Strikeout), // FontStyle字體的樣式,多個(gè)樣式,需要|線(xiàn)
Brushes.Black,
new RectangleF(r.Next(20), r.Next(7), img.Width, img.Height));
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//保存驗(yàn)證碼對(duì)象,指定是Jpeg格式
}
}
}
//畫(huà)噪點(diǎn)方法
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));
}
}
//隨機(jī)數(shù)
Random r = new Random();
//畫(huà)字符創(chuàng)
string GetCode(int point)
{
string txtStr = "ASF2345WE5R9F3HMBCZ455K";//這里的string字符串將會(huì)轉(zhuǎn)成 char數(shù)組,阿拉伯?dāng)?shù)字1和小寫(xiě)字母l最好別寫(xiě)在里面,會(huì)搞胡亂。
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;
}