public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
//创建位图,并且给指定边框的宽高
using (Image img=new Bitmap(80,25))
{
//创建画家对象,在img对象画字符串
using (Graphics g=Graphics.FromImage(img))
{
//设置位图的背景颜色,默认是黑色
g.Clear(Color.White);
//设置验证码的宽高, 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));
}
}
//随机数
Random r = new Random();
//画字符创
string GetCode(int point)
{
string txtStr = "ASF2345WE5R9F3HMBCZ455K";//这里的string字符串将会转成 char数组,阿拉伯数字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;
}
请发表评论