使用HttpHandler对象实现图片验证码

新建一个一般处理程序
引用三个命名空间:
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.SessionState;
继承接口:IRequiresSessionState
在这里插入图片描述

/一般处理程序中生成验证码:
Color[] colors = new Color[]
            {
                Color.Red,Color.Green,Color.Yellow,Color.Blue,Color.AliceBlue,Color.Aqua,Color.Bisque,Color.Brown
            };
            Image img = new Bitmap(100, 36);
            Graphics graphics = Graphics.FromImage(img);
            Random random = new Random(DateTime.Now.Millisecond);
            int charNum1 = random.Next(97, 122);
            int charNum2 = random.Next(97, 122);
            int charNum3 = random.Next(97, 122);
            int charNum4 = random.Next(97, 122);
            //保存验证码
            string validCode = string.Format("{0}{1}{2}{3}", (char)charNum1, (char)charNum2, (char)charNum3, (char)charNum4);
            context.Session["sn"] = validCode;
            Font font = new Font("宋体", 24);
            Brush brush1 = new SolidBrush(colors[random.Next(0, colors.Length-1)]);
            graphics.DrawString(((char)charNum1).ToString(), font, brush1, 7, -3);
            Brush brush2 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
            graphics.DrawString(((char)charNum2).ToString(), font, brush2, 26,-9);
            Brush brush3 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
            graphics.DrawString(((char)charNum3).ToString(), font, brush3, 50, 0);
            Brush brush4 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
            graphics.DrawString(((char)charNum4).ToString(), font, brush4, 70, -7);
            context.Response.ContentType = "image/jpeg";
            img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
            img.Dispose();    

在网页中添加

<img src="Handler.ashx?k=1" alt="看不清,换一张" class="pure-input-1-2" style="width: 100px; height: 36px;" onclick="this.src=this.src+1" />

注:Handler.ashx为一般处理程序名称
按以上操作完成即ok

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值