一般处理程序生成字母+数字验证码

本文介绍了一个简单的验证码生成器实现过程,包括使用C#生成随机字符串验证码、创建带干扰线的图片,并将验证码保存到session中以供后续验证使用。此外还提供了一段JavaScript代码用于刷新验证码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 public void ProcessRequest(HttpContext context)
    {

        string checkcode = Gent(5);
        context.Session["yzm"] = checkcode;
        Bitmap bit = new Bitmap(70, 22);
        Graphics gra = Graphics.FromImage(bit);
        try
        {
            Random random = new Random();
            gra.Clear(Color.White);
            //干扰线
            for (int i = 0; i < 20; i++)
            {
                int x1 = random.Next(bit.Width);
                int x2 = random.Next(bit.Width);
                int y1 = random.Next(bit.Height);
                int y2 = random.Next(bit.Height);
                gra.DrawLine(new Pen(Color.Red), x1, y1, x2, y2);
            }
            Font font = new Font("Arial", 12, (FontStyle.Bold|FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, bit.Width, bit.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            gra.DrawString(checkcode, font, brush, 2, 2);
            gra.DrawRectangle(new Pen(Color.Silver), 0, 0, bit.Width - 1, bit.Height - 1);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            bit.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            context.Response.ClearContent();
            context.Request.ContentType = "image/Gif";
            context.Response.BinaryWrite(ms.ToArray());


        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            bit.Dispose();
            gra.Dispose();
        }


    }
    private string Gent(int num)
    {
        string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] chars = str.ToCharArray();
        string code = "";


        Random ran = new Random();
        for (int i = 0; i < num; i++)
        {
            code += str.Substring(ran.Next(0, str.Length), 1);
        }
        return code;

    }


前台调用点击事件function

   var imgas = document.getElementById("");
            if (imgas != null) {
                imgas.src = imgas.src + "?";

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值