欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

理解C#生成验证码的过程

程序员文章站 2022-04-28 21:01:33
本文实例为大家介绍了生成验证码的详细过程,供大家参考,具体内容如下 生成验证码的类: using system; using system.collect...

本文实例为大家介绍了生成验证码的详细过程,供大家参考,具体内容如下

生成验证码的类:

using system;
using system.collections.generic;
using system.drawing;
using system.text;

namespace controllers.core.util
{
  /// <summary>
  /// 验证码
  /// </summary>
  public class verifycodehelper : adminbasecontroller
  {
    #region 变量
    /// <summary>
    /// 颜色表
    /// </summary>
    private static color[] colors = new color[]{
      color.fromargb(220,20,60),
      color.fromargb(128,0,128),
      color.fromargb(65,105,225),
      color.fromargb(70,130,180),
      color.fromargb(46,139,87),
      color.fromargb(184,134,11),
      color.fromargb(255,140,0),
      color.fromargb(139,69,19),
      color.fromargb(0,191,255),
      color.fromargb(95,158,160),
      color.fromargb(255,20,147),
      color.fromargb(255,165,0)};

    /// <summary>
    /// 字体表
    /// </summary>
    private static string[] fonts = new string[] { 
      "arial",
      "verdana", 
      "georgia", 
      "黑体" };

    /// <summary>
    /// 字体大小
    /// </summary>
    private static int fontsize = 22;
    #endregion

    #region 生成验证码图片
    /// <summary>
    /// 生成验证码图片
    /// </summary>
    public static bitmap createverifycodebmp(out string code)
    {
      int width = 120;
      int height = 40;
      bitmap bmp = new bitmap(width, height);
      graphics g = graphics.fromimage(bmp);
      random rnd = new random();

      //背景色
      g.fillrectangle(new solidbrush(color.white), new rectangle(0, 0, width, height));

      //文字
      stringbuilder sbcode = new stringbuilder();
      for (int i = 0; i < 4; i++)
      {
        string str = getchar(rnd);
        font font = getfont(rnd);
        color color = getcolor(rnd);
        g.drawstring(str, font, new solidbrush(color), new pointf((float)(i * width / 4.0), 0));
        sbcode.append(str);
      }
      code = sbcode.tostring();

      //噪音线
      for (int i = 0; i < 10; i++)
      {
        int x1 = rnd.next(bmp.width);
        int x2 = rnd.next(bmp.width);
        int y1 = rnd.next(bmp.height);
        int y2 = rnd.next(bmp.height);

        pen p = new pen(getcolor(rnd), 1);
        g.drawline(p, x1, y1, x2, y2);
      }

      //扭曲
      bmp = twistimage(bmp, true, 3, rnd.nextdouble() * math.pi * 2);
      g = graphics.fromimage(bmp);

      //噪点
      for (int i = 0; i < 100; i++)
      {
        int x1 = rnd.next(bmp.width);
        int y1 = rnd.next(bmp.height);

        pen p = new pen(getcolor(rnd), 1);
        g.drawrectangle(p, x1, y1, 1, 1);
      }

      //边框
      g.drawrectangle(new pen(new solidbrush(color.fromargb(153, 153, 153))), new rectangle(0, 0, width - 1, height - 1));

      return bmp;
    }
    #endregion

    #region 获取随机字符
    /// <summary>
    /// 获取随机字符
    /// </summary>
    private static string getchar(random rnd)
    {
      int n = rnd.next(0, 61);
      if (n <= 9)
      {
        return ((char)(48 + n)).tostring();
      }
      else if (n <= 35)
      {
        return ((char)(65 + n - 10)).tostring();
      }
      else
      {
        return ((char)(97 + n - 36)).tostring();
      }
    }
    #endregion

    #region 获取随机字体
    /// <summary>
    /// 获取随机字体
    /// </summary>
    private static font getfont(random rnd)
    {
      return new font(fonts[rnd.next(0, fonts.length)], fontsize, fontstyle.bold);
    }
    #endregion

    #region 获取随机颜色
    /// <summary>
    /// 获取随机颜色
    /// </summary>
    private static color getcolor(random rnd)
    {
      return colors[rnd.next(0, colors.length)];
    }
    #endregion

    #region 正弦曲线wave扭曲图片
    /// <summary>  
    /// 正弦曲线wave扭曲图片(edit by 51aspx.com)  
    /// </summary>  
    /// <param name="srcbmp">图片路径</param>  
    /// <param name="bxdir">如果扭曲则选择为true</param>  
    /// <param name="nmultvalue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>  
    /// <param name="dphase">波形的起始相位,取值区间[0-2*pi)</param>  
    private static system.drawing.bitmap twistimage(bitmap srcbmp, bool bxdir, double dmultvalue, double dphase)
    {
      system.drawing.bitmap destbmp = new bitmap(srcbmp.width, srcbmp.height);

      // 将位图背景填充为白色  
      system.drawing.graphics graph = system.drawing.graphics.fromimage(destbmp);
      graph.fillrectangle(new solidbrush(system.drawing.color.white), 0, 0, destbmp.width, destbmp.height);
      graph.dispose();

      double dbaseaxislen = bxdir ? (double)destbmp.height : (double)destbmp.width;

      for (int i = 0; i < destbmp.width; i++)
      {
        for (int j = 0; j < destbmp.height; j++)
        {
          double dx = 0;
          dx = bxdir ? (math.pi * 2 * (double)j) / dbaseaxislen : (math.pi * 2 * (double)i) / dbaseaxislen;
          dx += dphase;
          double dy = math.sin(dx);

          // 取得当前点的颜色  
          int noldx = 0, noldy = 0;
          noldx = bxdir ? i + (int)(dy * dmultvalue) : i;
          noldy = bxdir ? j : j + (int)(dy * dmultvalue);

          system.drawing.color color = srcbmp.getpixel(i, j);
          if (noldx >= 0 && noldx < destbmp.width
           && noldy >= 0 && noldy < destbmp.height)
          {
            destbmp.setpixel(noldx, noldy, color);
          }
        }
      }

      return destbmp;
    }
    #endregion

  }
}

验证码页面action:

public actionresult verifycode()
{
  string code;
  bitmap bmp = verifycodehelper.createverifycodebmp(out code);
  bitmap newbmp = new bitmap(bmp, 108, 36);
  httpcontext.session["verifycode"] = code;

  response.clear();
  response.contenttype = "image/bmp";
  newbmp.save(response.outputstream, system.drawing.imaging.imageformat.bmp);

  return view();
}

说明:前台页面为空的cshtml页面,验证码的值放在session中。

使用验证码的页面:

显示验证码的img:

<img id="verifycode" src="" alt="验证码" style="vertical-align: middle;" />
页面加载完成后,显示验证码(注意,要加上时间戳,不然刷新页面时验证码不刷新):

$(function () {
  //刷新验证码
  $("#refreshverifycode").click(function () {
    refreshverifycode(); //刷新验证码
  });
  $("#verifycode").click(function () {
    refreshverifycode(); //刷新验证码
  });
  refreshverifycode();
});

刷新验证码:

//刷新验证码
function refreshverifycode() {
  $("#verifycode").attr("src", "verifycode?t=" + new date().valueof());
}
 

判断用户输入的文本是否与验证码相同的action:

public actionresult checkvcode(string vcode)
{
  if (httpcontext.session["verifycode"].tostring().tolower() == vcode.tolower())
  {
    dictionary<string, object> dic = new dictionary<string, object>();
    dic["ok"] = true;
    return content(jsonconvert.serializeobject(dic));
  }
  else
  {
    dictionary<string, object> dic = new dictionary<string, object>();
    dic["ok"] = false;
    return content(jsonconvert.serializeobject(dic));
  }
}

以上就是本文的全部内容,希望对大家学习c#生成验证码的方法有所帮助。