• ASP.NET网页验证码常用方法


    验证码生产类

      1 using System;
      2 using System.Data;
      3 using System.Configuration;
      4 
      5 using System.Web;
      6 using System.Web.Security;
      7 using System.Web.UI;
      8 using System.Web.UI.HtmlControls;
      9 using System.Web.UI.WebControls;
     10 using System.Web.UI.WebControls.WebParts;
     11 
     12 using System.Drawing;
     13 using System.IO;
     14 using System.Drawing.Imaging;
     15 
     16 /// <summary>  
     17 /// Summary description for validatedCode  
     18 /// </summary>  
     19 public class ValidatedCode
     20 {
     21     #region  验证码长度(默认4个验证码的长度)
     22     int length = 4;
     23     public int Length
     24     {
     25         get { return length; }
     26         set { length = value; }
     27     }
     28     #endregion
     29 
     30     #region 验证码字体大小(为了显示扭曲效果,默认40像素,可以自行修改)
     31     int fontSize = 40;
     32     public int FontSize
     33     {
     34         get { return fontSize; }
     35         set { fontSize = value; }
     36     }
     37     #endregion
     38 
     39     #region 边框补(默认1像素)
     40     int padding = 2;
     41     public int Padding
     42     {
     43         get { return padding; }
     44         set { padding = value; }
     45     }
     46     #endregion
     47 
     48     #region 是否输出燥点(默认不输出)
     49     bool chaos = true;
     50     public bool Chaos
     51     {
     52         get { return chaos; }
     53         set { chaos = value; }
     54     }
     55     #endregion
     56 
     57     #region 输出燥点的颜色(默认灰色)
     58     Color chaosColor = Color.LightGray;
     59     public Color ChaosColor
     60     {
     61         get { return chaosColor; }
     62         set { chaosColor = value; }
     63     }
     64     #endregion
     65 
     66     #region 自定义背景色(默认白色)
     67     Color backgroundColor = Color.White;
     68     public Color BackgroundColor
     69     {
     70         get { return backgroundColor; }
     71         set { backgroundColor = value; }
     72     }
     73     #endregion
     74 
     75     #region 自定义随机颜色数组
     76     Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
     77     public Color[] Colors
     78     {
     79         get { return colors; }
     80         set { colors = value; }
     81     }
     82     #endregion
     83 
     84     #region 自定义字体数组
     85     string[] fonts = { "Arial", "Georgia" };
     86     public string[] Fonts
     87     {
     88         get { return fonts; }
     89         set { fonts = value; }
     90     }
     91     #endregion
     92 
     93     #region 自定义随机码字符串序列(使用逗号分隔)
     94     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";
     95     public string CodeSerial
     96     {
     97         get { return codeSerial; }
     98         set { codeSerial = value; }
     99     }
    100     #endregion
    101 
    102     #region 产生波形滤镜效果
    103 
    104     private const double PI = 3.1415926535897932384626433832795;
    105     private const double PI2 = 6.283185307179586476925286766559;
    106 
    107     /// <summary>  
    108     /// 正弦曲线Wave扭曲图片(Edit By 51aspx.com)  
    109     /// </summary>  
    110     /// <param name="srcBmp">图片路径</param>  
    111     /// <param name="bXDir">如果扭曲则选择为True</param>  
    112     /// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>  
    113     /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>  
    114     /// <returns></returns>  
    115     public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
    116     {
    117         System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
    118 
    119         // 将位图背景填充为白色  
    120         System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
    121         graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
    122         graph.Dispose();
    123 
    124         double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
    125 
    126         for (int i = 0; i < destBmp.Width; i++)
    127         {
    128             for (int j = 0; j < destBmp.Height; j++)
    129             {
    130                 double dx = 0;
    131                 dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
    132                 dx += dPhase;
    133                 double dy = Math.Sin(dx);
    134 
    135                 // 取得当前点的颜色  
    136                 int nOldX = 0, nOldY = 0;
    137                 nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
    138                 nOldY = bXDir ? j : j + (int)(dy * dMultValue);
    139 
    140                 System.Drawing.Color color = srcBmp.GetPixel(i, j);
    141                 if (nOldX >= 0 && nOldX < destBmp.Width
    142                  && nOldY >= 0 && nOldY < destBmp.Height)
    143                 {
    144                     destBmp.SetPixel(nOldX, nOldY, color);
    145                 }
    146             }
    147         }
    148 
    149         return destBmp;
    150     }
    151 
    152 
    153 
    154     #endregion
    155 
    156     #region 生成校验码图片
    157     public Bitmap CreateImageCode(string code)
    158     {
    159         int fSize = FontSize;
    160         int fWidth = fSize + Padding;
    161 
    162         int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;
    163         int imageHeight = fSize * 2 + Padding;
    164 
    165         System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);
    166 
    167         Graphics g = Graphics.FromImage(image);
    168 
    169         g.Clear(BackgroundColor);
    170 
    171         Random rand = new Random();
    172 
    173         //给背景添加随机生成的燥点  
    174         if (this.Chaos)
    175         {
    176 
    177             Pen pen = new Pen(ChaosColor, 0);
    178             int c = Length * 10;
    179 
    180             for (int i = 0; i < c; i++)
    181             {
    182                 int x = rand.Next(image.Width);
    183                 int y = rand.Next(image.Height);
    184 
    185                 g.DrawRectangle(pen, x, y, 1, 1);
    186             }
    187         }
    188 
    189         int left = 0, top = 0, top1 = 1, top2 = 1;
    190 
    191         int n1 = (imageHeight - FontSize - Padding * 2);
    192         int n2 = n1 / 4;
    193         top1 = n2;
    194         top2 = n2 * 2;
    195 
    196         Font f;
    197         Brush b;
    198 
    199         int cindex, findex;
    200 
    201         //随机字体和颜色的验证码字符  
    202         for (int i = 0; i < code.Length; i++)
    203         {
    204             cindex = rand.Next(Colors.Length - 1);
    205             findex = rand.Next(Fonts.Length - 1);
    206 
    207             f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
    208             b = new System.Drawing.SolidBrush(Colors[cindex]);
    209 
    210             if (i % 2 == 1)
    211             {
    212                 top = top2;
    213             }
    214             else
    215             {
    216                 top = top1;
    217             }
    218 
    219             left = i * fWidth;
    220 
    221             g.DrawString(code.Substring(i, 1), f, b, left, top);
    222         }
    223 
    224         //画一个边框 边框颜色为Color.Gainsboro  
    225         g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
    226         g.Dispose();
    227 
    228         //产生波形(Add By 51aspx.com)  
    229         image = TwistImage(image, true, 8, 4);
    230 
    231         return image;
    232     }
    233     #endregion
    234 
    235     #region 将创建好的图片输出到页面
    236     public void CreateImageOnPage(string code, HttpContext context)
    237     {
    238         System.IO.MemoryStream ms = new System.IO.MemoryStream();
    239         Bitmap image = this.CreateImageCode(code);
    240 
    241         image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    242 
    243         context.Response.ClearContent();
    244         context.Response.ContentType = "image/Jpeg";
    245         context.Response.BinaryWrite(ms.GetBuffer());
    246 
    247         ms.Close();
    248         ms = null;
    249         image.Dispose();
    250         image = null;
    251     }
    252     #endregion
    253 
    254     #region 生成随机字符码
    255     public string CreateVerifyCode(int codeLen)
    256     {
    257         Random CheckNum = new Random();
    258        
    259         string code = "";
    260 
    261         for (int i = 0; i < codeLen; i++)
    262         {
    263           if(i%2==0)
    264               code += (Convert.ToChar(CheckNum.Next(97, 122))).ToString();
    265           else
    266               code += CheckNum.Next(0, 9).ToString();
    267         }
    268 
    269         return code;
    270     }
    271     public string CreateVerifyCode()
    272     {
    273         return CreateVerifyCode(4);
    274     }
    275     #endregion
    276 }
    View Code

    验证码显示页面

     1 using System;
     2 using System.Collections;
     3 using System.Configuration;
     4 using System.Data;
     5 using System.Web;
     6 using System.Web.Security;
     7 using System.Web.UI;
     8 using System.Web.UI.HtmlControls;
     9 using System.Web.UI.WebControls;
    10 using System.Web.UI.WebControls.WebParts;
    11 
    12 using System.Drawing.Drawing2D;
    13 using System.Drawing;
    14 using System.Drawing.Imaging;
    15 using System.IO;
    16 using Px_CSLibrary.Public;
    17 public partial class CheckCode : System.Web.UI.Page
    18 {
    19 
    20 
    21     protected void Page_Load(object sender, EventArgs e)
    22     {
    23         ValidatedCode v = new ValidatedCode();
    24         string checkNum = v.CreateVerifyCode();            //取随机码  
    25         Session["Checkcode"] = checkNum;
    26         HttpCookie cookCode = new HttpCookie("Check");
    27         cookCode.Values.Add("code", checkNum);//把随机验证码保存Cookie
    28         cookCode.Expires = DateTime.Now.AddMilliseconds(60000);
    29         Response.Cookies.Add(cookCode);
    30          
    31         v.CreateImageOnPage(checkNum, this.Context);       // 输出图片  
    32 
    33     }
    34 
    35 }
    View Code

    页面标签引用

    <dd> <img id="CheckCode" alt="验证码" width="85px" height="25px" style="cursor: pointer" src="CheckCode.aspx" onclick="GetCode()" /></dd>
    <dd>
    <a href="javascript:void(0)" onclick="GetCode();">刷新</a>
    </dd>
  • 相关阅读:
    C++多线程二
    C++多线程一
    定义抽象数据类型
    泛型函数
    关联容器(map):支持高效查找的容器,一种键值对的集合。
    字符串拆成单词的另一种实现
    将字符串拆成单词,并算最长的长度
    重载,排序,集合实例
    程序调用动态链接库中的方法,位图,类
    用bosybox制作文件系统
  • 原文地址:https://www.cnblogs.com/loyung/p/4691183.html
走看看 - 开发者的网上家园