发布作者: 云峥
百度收录: 正在检测是否收录...
作品采用: 《 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 》许可协议授权
通常用于Web应用程序中的用户登录、注册、表单提交等场景,通过让用户输入验证码来防止恶意的自动化脚本提交表单,提高系统的安全性,防止垃圾信息的产生等。
public partial class captcha : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 生成随机字符串
string captchaText = GenerateRandomCode(4);
Session["captcha"] = captchaText; // 存储在 Session 以便验证
// 创建图像
Bitmap bitmap = new Bitmap(100, 40);
Graphics g = Graphics.FromImage(bitmap);
g.Clear(Color.White);
// 设置字体
Font font = new Font("Arial", 20, FontStyle.Bold);
Brush brush = new SolidBrush(Color.Black);
Random rand = new Random();
// 添加干扰线
for (int i = 0; i < 6; i++)
{
Pen pen = new Pen(Color.Gray);
int x1 = rand.Next(100);
int y1 = rand.Next(40);
int x2 = rand.Next(100);
int y2 = rand.Next(40);
g.DrawLine(pen, x1, y1, x2, y2);
}
// 绘制验证码
g.DrawString(captchaText, font, brush, 10, 5);
g.Flush();
// 输出图像到浏览器
Response.ContentType = "image/png";
bitmap.Save(Response.OutputStream, ImageFormat.Png);
// 释放资源
g.Dispose();
bitmap.Dispose();
}
private string GenerateRandomCode(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
char[] buffer = new char[length];
for (int i = 0; i < length; i++)
{
buffer[i] = chars[random.Next(chars.Length)];
}
return new string(buffer);
}
}
—— 评论区 ——