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

.net生成验证码

程序员文章站 2024-02-12 14:30:34
本文为大家分享了.net生成验证码所有代码,大家可以动手操作一下,会有意想不到的收获。 先给大家看看效果图: 页面代码:

本文为大家分享了.net生成验证码所有代码,大家可以动手操作一下,会有意想不到的收获。

先给大家看看效果图:

.net生成验证码

页面代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>验证码</title>
  <script type="text/javascript">
    //换一张
    function change() {
      var img = document.getelementbyid("validatecode");
      img.src = img.src + '?';
    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <table>
      <tr>
        <th>
          验证码
        </th>
        <td>
          <asp:textbox runat="server" id="tbcheckcode" cssclass="small" maxlength="4"></asp:textbox>
        </td>
        <td>
          <img src="verifycode.aspx" id="validatecode" alt="换一张" onclick="javascript:change()" />
        </td>
        <td>
          <a id="changecode" href="#" onclick="javascript:change()">换一张</a>
        </td>
      </tr>
      <tr>
        <td>
          <asp:button runat="server" id="loginsubmit" onclick="loginsubmits" text="登录" />
        </td>
      </tr>
    </table>
  </div>
  </form>
</body>
</html>

后台代码:

    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="sender"></param>
    protected void loginsubmits(object sender, eventargs e)
    {
      checklogin();
    }

    #region 私有方法
    #region
    public static boolean isnotnull(object str)
    {
      return !isnull(str);
    }
    public static boolean isnull(object str)
    {
      return str == null;
    }
    public static void show(system.web.ui.page page, string msg)
    {
      page.clientscript.registerstartupscript(page.gettype(), "message",
        "<script language='javascript' defer>alert('" + msg.tostring() + "');</script>");
    }
    #endregion

    private void checklogin()
    {
      if (tbcheckcode.text.trim() == "")
      {
        show(this, "验证码不能为空!");
        return;
      }
      else
      {
        if (isnotnull(session["validatecheckcode"]))
        {
          if (tbcheckcode.text.trim() != session["validatecheckcode"].tostring())
          {
            show(this, "验证码填写不正确!");
            tbcheckcode.text = "";
            return;
          }
        }
        else
        {
          show(this, "请刷新验证码!");
          return;
        }
      }
    }
    #endregion
  }
}

生成验证码:

using system;
using system.drawing;
using system.text;
using system.web;

namespace web.text
{
  public partial class verifycode : system.web.ui.page
  {
    public encoding gb = encoding.getencoding("gb2312");

    protected void page_load(object sender, eventargs e)
    {
      verifycode v = new verifycode();

      v.length = this.length;
      v.fontsize = this.fontsize;
      v.chaos = this.chaos;
      v.backgroundcolor = this.backgroundcolor;
      v.chaoscolor = this.chaoscolor;
      v.codeserial = this.codeserial;
      v.colors = this.colors;
      v.fonts = this.fonts;
      v.padding = this.padding;
      string code = v.createverifycode(); //取随机码
      v.createimageonpage(code, this.context); // 输出图片
      response.cookies.add(new httpcookie("checkcode", code.toupper())); // 使用cookies取验证码的值

      system.web.httpcontext.current.session["validatecheckcode"] = code;
      //return checkcode;
    }

    #region 验证码长度(默认4个验证码的长度)

    private int length = 4; 

    public int length
    {
      get { return length; }
      set { length = value; }
    }

    #endregion

    #region 验证码字体大小(为了显示扭曲效果,默认40像素,可以自行修改)

    private int fontsize = 12;

    public int fontsize
    {
      get { return fontsize; }
      set { fontsize = value; }
    }

    #endregion

    #region 边框补(默认1像素)

    private int padding = 1;

    public int padding
    {
      get { return padding; }
      set { padding = value; }
    }

    #endregion

    #region 是否输出燥点(默认不输出)

    private bool chaos = true;

    public bool chaos
    {
      get { return chaos; }
      set { chaos = value; }
    }

    #endregion

    #region 输出燥点的颜色(默认灰色)

    private color chaoscolor = color.lightgray;

    public color chaoscolor
    {
      get { return chaoscolor; }
      set { chaoscolor = value; }
    }

    #endregion

    #region 自定义背景色(默认白色)

    private color backgroundcolor = color.white;

    public color backgroundcolor
    {
      get { return backgroundcolor; }
      set { backgroundcolor = value; }
    }

    #endregion

    #region 自定义随机颜色数组

    private color[] colors =
    {
      color.black, color.red, color.darkblue, color.green, color.orange, color.brown,
      color.darkcyan, color.purple
    };

    public color[] colors
    {
      get { return colors; }
      set { colors = value; }
    }

    #endregion

    #region 自定义字体数组

    private string[] fonts = {"arial", "georgia"};

    public string[] fonts
    {
      get { return fonts; }
      set { fonts = value; }
    }

    #endregion

    #region 自定义随机码字符串序列(使用逗号分隔)

    private string codeserial = "0,1,2,3,4,5,6,7,8,9";
    // string codeserial = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
    // string codeserial = "殃,央,鸯,秧,杨,扬,佯,疡,羊,洋,阳,氧,仰,痒,养,样,漾,邀,腰,妖,瑶,摇,尧,遥,窑,谣,姚,咬,舀,药,要,耀,椰,噎,耶,爷,野,冶,也,页,掖,业,叶,曳,腋,夜,液,一,壹,医,揖,铱,依,伊,衣,颐,夷,遗,移,仪,胰,疑,沂,宜,姨,彝,椅,蚁,倚,已,乙,矣,以,艺,抑,易,邑,屹,亿,役,臆,逸,肄,疫,亦,裔,意,毅,忆,义,益,溢,诣,议,谊,译,异,翼,翌,绎,茵,荫,因,殷,音,阴,姻,吟,银,淫,寅,饮,尹,引,隐,印,英,樱,婴,鹰,应,缨,莹,萤,营,荧,蝇,迎,赢,盈,影,颖,硬,映,哟,拥,佣,臃,痈,庸,雍,踊,蛹,咏,泳,涌,永,恿,勇,用,幽,优,悠,忧,尤,由,邮,铀,犹,油,游,酉,有,友,右,佑,釉,诱,又,幼,迂,淤,于,盂,榆,虞,愚,舆,余,俞,逾,鱼,愉,渝,渔,隅,予,娱,雨,与,屿,禹,株,蛛,朱,猪,诸,诛,逐,竹,烛,煮,拄,瞩,嘱,主,著,柱,助,蛀,贮,铸,筑,住,注,祝,驻,抓,爪,拽,专,砖,转,撰,赚,篆,桩,庄,装,妆,撞,壮,状,椎,锥,追,赘,坠,缀,谆,准,捉,拙,卓,桌,琢,茁,酌,啄,着,灼,浊,兹,咨,资,姿,滋,淄,孜,紫,仔,籽,滓,子,自,渍,字,鬃,棕,踪,宗,综,总,纵,邹,走,奏,揍,租,足,卒,族,祖,诅,阻,组,钻,纂,嘴,醉,最,罪,尊,遵,昨,左,佐,柞,做,作,坐,座";
    public string codeserial
    {
      get { return codeserial; }
      set { codeserial = value; }
    }

    #endregion

    //产生波形滤镜效果

    #region 产生波形滤镜效果

    private const double pi = 3.1415926535897932384626433832795;
    private const double pi2 = 6.283185307179586476925286766559;

    /**/

    /// <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>
    /// <returns></returns>
    public 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 ? (pi2*(double) j)/dbaseaxislen : (pi2*(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

    #region 生成校验码图片

    public bitmap createimagecode(string code)
    {
      int fsize = fontsize;
      int fwidth = fsize + padding;

      int imagewidth = (int) (code.length*fwidth) + 4 + padding*2;
      int imageheight = fsize*2 + padding;

      system.drawing.bitmap image = new system.drawing.bitmap(imagewidth, imageheight);

      graphics g = graphics.fromimage(image);

      g.clear(backgroundcolor);

      random rand = new random();

      //给背景添加随机生成的燥点
      if (this.chaos)
      {

        pen pen = new pen(chaoscolor, 0);
        int c = length*10;

        for (int i = 0; i < c; i++)
        {
          int x = rand.next(image.width);
          int y = rand.next(image.height);

          g.drawrectangle(pen, x, y, 1, 1);
        }
      }

      int left = 0, top = 0, top1 = 1, top2 = 1;

      int n1 = (imageheight - fontsize - padding*2);
      int n2 = n1/4;
      top1 = n2;
      top2 = n2*2;

      font f;
      brush b;

      int cindex, findex;

      #region 随机字体和颜色的验证码字符

      for (int i = 0; i < code.length; i++)
      {
        cindex = rand.next(colors.length - 1);
        findex = rand.next(fonts.length - 1);

        f = new system.drawing.font(fonts[findex], fsize, system.drawing.fontstyle.bold);
        b = new system.drawing.solidbrush(colors[cindex]);

        if (i%2 == 1)
        {
          top = top2;
        }
        else
        {
          top = top1;
        }

        left = i*fwidth;

        g.drawstring(code.substring(i, 1), f, b, left, top);
      }

      //画一个边框 边框颜色为color.gainsboro
      g.drawrectangle(new pen(color.gainsboro, 0), 0, 0, image.width - 1, image.height - 1);
      g.dispose();

      //产生波形
      //image = twistimage(image, true, 8, 4);

      return image;
    }

    #endregion

    //将创建好的图片输出到页面
    public void createimageonpage(string code, httpcontext context)
    {
      system.io.memorystream ms = new system.io.memorystream();
      bitmap image = this.createimagecode(code);

      image.save(ms, system.drawing.imaging.imageformat.jpeg);

      context.response.clearcontent();
      context.response.contenttype = "image/jpeg";
      context.response.binarywrite(ms.getbuffer());

      ms.close();
      ms = null;
      image.dispose();
      image = null;
    }

    #endregion

    #region 生成随机字符码

    public string createverifycode(int codelen)
    {
      if (codelen == 0)
      {
        codelen = length;
      }

      string[] arr = codeserial.split(',');

      string code = "";

      int randvalue = -1;

      random rand = new random(unchecked((int) datetime.now.ticks));

      for (int i = 0; i < codelen; i++)
      {
        randvalue = rand.next(0, arr.length - 1);

        code += arr[randvalue];
      }

      return code;
    }

    public string createverifycode()
    {
      return createverifycode(0);
    }

    #endregion
  }
}

是不是很有成就感,为大家分享的代码很完整,大家可以在这个基础进行扩展,希望大家喜欢。