C#使用GDI+实现生成验证码

 

一、概述

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

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

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

 

二、一般处理程序

    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="width: 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>");
}

关于C#使用GDI+实现生成验证码的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程宝库

C#中Lambda表达式的用法: 一、介绍1、"Lambda表达式"是一个特殊的匿名函数,简化了匿名委托的使用,是一种高效的类似于函数式编程的表达式,Lambda简化了开发中需要编写的代码量。2、它可以包含表达式和语句,并且可用于 ...