1:第一步,自定义一个数组方法
public void CateGory() {
string []code = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "A", "B", "C", "D", "E", "E", "F", "G", "H", "I", "J", "1", "2", "3", "4", "5", "6", "7", "8", "0", "9"};
//随机
Random randow = new Random();
for (int i = 0; i < 5; i++)//生成5位数的验证码
{
result+=code[randow.Next(0,code.Length)];//将验证码数字加到变量中
}
}
public string result;//申明接收验证码的变量
2:画出验证码保存为图片
public void DrawCode(HttpContext hc) {
Random randow = new Random();
Image img = new Bitmap(100,30);//准备画布
Graphics gr=Graphics.FromImage(img);//绘制GID精灵
Pen p = new Pen(Color.Black,1);//画笔;第一个参数表示画笔的颜色,第二个参数画笔的宽度
gr.DrawRectangle(p, 0, 0, 100, 30);//绘制矩形
gr.Clear(Color.White);//清空画布
//画出验证码
for (int i = 0; i < result.Length; i++)
{
gr.DrawString(result[i].ToString(),new Font ("微软雅黑",15),new SolidBrush(Color.FromArgb(randow.Next(0,100),randow.Next(0,100),randow.Next(0,100))),i*20,randow.Next(0,5));
gr.DrawLine(p, randow.Next(0, 40), randow.Next(0, 25), randow.Next(40, 80), randow.Next(0, 25));
}
Brush dot = new SolidBrush(Color.Blue);
//画点
for (int i = 0; i < 100; i++)
{
gr.FillEllipse(dot, randow.Next(0, 80), randow.Next(0, 25), 2f, 2f);
}
hc.Response.ContentType = "image/jpeg";// 更换宣布渲染格式
img.Save(hc.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); //保存渲染结果,图片
}
.Ashx输出验证码;
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "image/gif";
CateGory();
DrawCode(context);
}
3:前台展示:<img src="Code/CodeImage.ashx" id="img"/><a href="#" id="qi" onclick="ss();">点击切换</a>
<script>
function ss() {
document.getElementById('img').src = "Code/CodeImage.ashx?d=" + Math.random();
//点击切换验证码
}
</script>
是是 水水