protected string GetVCode(int num) //生成验证码的方法
{
char[] cha = new char[] {'1','2','3','a','b','c','e','f' }; //定义一个char数组
string vcode=string.Empty; //定义一个空string字符串变量准备接收数据
Random r = new Random(); //实例化Random
for (int i = 0; i < num; i++) //循环的在数组中随机取值
{
vcode += cha[r.Next(0, cha.Length - 1)].ToString();
}
return vcode;
}
public void DrawPoints(Image img, Graphics g, int num) //绘制干扰点的方法
{
Random r = new Random();
//定义点的x轴的坐标
int x;
//定义点的y轴的坐标
int y;
//随机生成的第一个点
Point p1;
Point p2;
for (int i = 0; i < num; i++)
{
//给x生成随机(这个数必须在图片中)
x = r.Next(img.Width);
y = r.Next(img.Height);
//创建第一个点
p1 = new Point(x, y);
p2 = new Point(x + 2, y + 2);
//将两个点连接起来
g.DrawLine(Pens.Black, p1, p2);
}
}
public void ProcessRequest(HttpContext context)
{
using (Image img = new Bitmap(65, 30)) //定义一个画布,width=65,height=30
{
using (Graphics g = Graphics.FromImage(img)) //为画布定义画家
{
g.Clear(Color.White); //清楚整个绘面并且指定颜色填充
g.DrawRectangle(Pens.Black, 0, 0, img.Width - 1, img.Height - 1); //描绘边框
g.DrawString(GetVCode(4), new Font("微软雅黑", 16, FontStyle.Italic | FontStyle.Strikeout), Brushes.Red, 0, 0); //将获得string类型验证码画出来
DrawPoints(img, g, 50); //加干扰点
}
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); //以二进制模式输出并且保存为指定格式
}
}
<tr>
<th>验证码:</th>
<td><input type="text" name="VCode" /><img id="img" src="/VCode.ashx" /></td>
</tr>