• C#(99):GDI+ 实例:绘制验证码


    一、概述

    一般处理程序 ashx :它没有服务器控件,用response输出什么就是什么。

    生成验证码原理:产生随机字符,并将字符生成为图片,同时储存到Session里去,然后验证用户输入的内容是否与Session中的验证码相符即可。

    效果图:用户可以点击切换验证码信息。

    image

    二、一般处理程序

    public class CheckCodeHandler : IHttpHandler, IRequiresSessionState//使用到Session,需要实现此接口IRequiresSessionState
        {
            private int intLength = 5;        //长度
            private string strIdentify = "Identify"; //随机字串存储键值,以便存储到Session中
    
    
            /// <summary>
            /// 生成验证图片核心代码
            /// </summary>
            /// <param name="context"></param>
            public void ProcessRequest(HttpContext context)
            {
                //背景用白色填充
                Bitmap map = new Bitmap(200, 60);
                Graphics g = Graphics.FromImage(map);
                g.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
    
                //将随机生成的字符串绘制到图片上
                string letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
                Random r = new Random();
                StringBuilder s = new StringBuilder();
                Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
    
                for (int i = 0; i < intLength; i++)
                {
                    s.Append(letters.Substring(r.Next(0, letters.Length - 1), 1));
                    g.DrawString(s[s.Length - 1].ToString(), font, new SolidBrush(Color.Blue), i * 38, r.Next(0, 15));
                }
                font.Dispose();
                context.Session[strIdentify] = s.ToString(); //先保存在Session中,验证与用户输入是否一致
    
                //生成干扰线条,混淆背景
                Pen pen = new Pen(new SolidBrush(Color.Blue), 2);
                for (int i = 0; i < 10; i++)
                {
                    g.DrawLine(pen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
                }
                pen.Dispose();
    
                //设置输出流图片格式
                context.Response.ContentType = "image/gif";
                map.Save(context.Response.OutputStream, ImageFormat.Gif);
                map.Dispose();
    
                context.Response.End();
            }
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
    }

    三、在页面调用

    <img src="CheckCodeHandler.ashx" alt="验证码" style=" 60px; height: 24px" />
    if (this.TextBox1.Text.ToUpper().Trim() != Session["strIdentify"].ToString().ToUpper().Trim())
    {
        Response.Write("<script>alert('验证码不正确')</script>");
    }
    else
    {
        Response.Write("<script>alert('登录成功')</script>");
    }
  • 相关阅读:
    MySQL数据库之索引
    python面向对象编程
    linux端口占用
    lintcode
    java基础
    lintcode
    linux 常用命令
    Docker & Kubernates
    angular preparation
    java 命令行
  • 原文地址:https://www.cnblogs.com/springsnow/p/9433975.html
Copyright © 2020-2023  润新知