Asp.net中GDI+生成验证码

Register.aspx

// 当点击验证码图片时,自动重新导向一次authcode.aspx,就重新刷新一次验证码
$('#authimage').click(function() {
$(this).attr("src", "authcode.aspx");
});


验证码:<input id="authcode" type="text" class="required" name="authcode" />
<img src="authcode.aspx" width="60px" height="30px" style="cursor:pointer" id="authimage"/>
注意,这个验证码图片的路径是一个动态页面!我们就在这个动态页面中利用GDI+技术绘制出验证码

authcode.cs
public partial class authcode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 验证码中可能出现的字符
string authCodeString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// 验证码字符集合长度
int length = authCodeString.Length;
// 绘制字符字体
Font f = new Font("宋体", 24, FontStyle.Bold);
// 绘制验证码的画刷对象
Brush b = null;
// 绘制验证码的颜色
Color brushColor = new Color();
Bitmap image = new Bitmap(80, 40);
Graphics g = Graphics.FromImage(image);
g.Clear(Color.Gray);// 设置背景

string authCode = string.Empty;// 整个显示给用户的验证码
string code = string.Empty; // 当前绘制的验证码
Random random = new Random();
for (int i = 0; i < 4; i++)
{
// 取余保证current长度不会超过验证码字符集合长度
int current = random.Next((DateTime.Now.Millisecond) % length);

// 验证码字符集合任意截取一个字符
code = authCodeString.Substring(current, 1);
authCode += code;
brushColor = Color.FromArgb(random.Next(255), random.Next(255), random.Next(255));
b = new SolidBrush(brushColor);

// 绘制刚刚得到的字符串
g.DrawString(code, f, b, i * 15, 2);
}
Response.Clear();
Response.ContentType = "image/pjpeg";
// 将对象保存到Response输出流中
image.Save(Response.OutputStream, ImageFormat.Jpeg);
image.Dispose();
Session["authCode"] = authCode; // 在服务器端保存验证码,用来比较
Response.End();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值