这里是使用服务器端代码生成验证码技术:
1、创建验证码的页面
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
public partial class ValidateCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.CacheControl = "no-cache"; //使用js脚本更换图片时可以及时更新
string code = CreateRandomCode(4);
Session["code"] = code;
CreateImage(code);
}
//产生随机数函数
private string CreateRandomCode(int codeCount)
{
string temp = "0,1,2,3,4,5,6,7,8,9";
string[] tempArray = temp.Split(',');
string randomCode = "";
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
randomCode += tempArray[rand.Next(10)];
}
return randomCode;
}
private void CreateImage(string checkCode)
{
//画图:
//画图需要画板(纸张或其他),画笔,颜料等。
Bitmap image = new Bitmap(60, 25); //纸张(画板)
Graphics g = Graphics.FromImage(image); //画笔
Brush b = new SolidBrush(Color.BlueViolet); //颜料
Font f = new Font("Kristen ITC", 16); //字体
Random rand = new Random();
g.Clear(Color.White); //清空图片背景色
int x, y;
x = y = 0;
for (int i = 0; i < 4; i++)
{
g.DrawString(checkCode[i].ToString(), f, b, x, y); //画字符串
x += rand.Next(6,14);
y = rand.Next(-3,3);
}
//#region 增加干扰
//Random random = new Random();
画图片的前景噪音点
//for (int i = 0; i < 100; i++)
//{
// int x = random.Next(image.Width);
// int y = random.Next(image.Height);
// image.SetPixel(x, y, Color.FromArgb(random.Next()));
//}
画图片的背景噪音线
//for (int i = 0; i < 10; i++)
//{
// int x1 = random.Next(image.Width);
// int x2 = random.Next(image.Width);
// int y1 = random.Next(image.Height);
// int y2 = random.Next(image.Height);
// g.DrawLine(new Pen(Color.BlueViolet), x1, y1, x2, y2);
//}
//#endregion
Response.ContentType = "image/jpeg"; //输出类型
image.Save(Response.OutputStream, ImageFormat.Jpeg); //将图片存入输入流中
g.Dispose(); //释放资源
image.Dispose();
Response.End();
}
}
2、在注册页面使用验证码
<script type="text/javascript">
function changeImg(img){
img.src = "ValidateCode.aspx";
}
</script>
<img alt="点击更换图片" οnclick="changeImg(this)" src="ValidateCode.aspx" /></td>