首页 > 代码库 > 字母汉子组合的验证码,包括实现看不清换一个的功能

字母汉子组合的验证码,包括实现看不清换一个的功能

1、写一个验证码,前台什么都不用写,这是CreateVerificationCode_Page.aspx.cs后台代码

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;

namespace 验证码
{
    public partial class CreateVerificationCode_Page : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // 在此处放置用户代码以初始化页面
            CreateCheckCodeImage(GenerateCheckCode(5));//charNum=5,
            Session["CheckCode"] = GenerateCheckCode(5);
        }

        #region Web 窗体设计器生成的代码
        override protected void OnInit(EventArgs e)
        {
            // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。       
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new EventHandler(Page_Load);
        }
        #endregion

        private string GenerateCheckCode( int charNum)//charNum是验证码要显示的多少个字母或数字
        {
            int number;
            char code;
            string checkCode = String.Empty;
            Random random = new Random();
            for (int i = 0; i < charNum; i++)
            {
                number = random.Next();
                if (number % 2 == 0)//转换成ASCII码得到相加后的数 再转换成字符char
                {
                    int x = number % 10;
                    if (x == 0 || x == 1)
                    {
                        code = (char)(‘0‘ + (char)(3));
                    }
                    else
                    {
                        code = (char)(‘0‘ + (char)(number % 10));
                    }
                }
                else
                {
                    int y = number % 26;
                    if (y == 8 || y == 14)
                    {
                        code = (char)(‘A‘ + (char)(0));
                    }
                    else
                    {
                        code = (char)(‘A‘ + (char)(number % 26));
                    }
                }
                checkCode += code.ToString();
            }
            // Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
            return checkCode;
        }

        private void CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
            {
                return;
            }           
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 20); Graphics g = Graphics.FromImage(image);
            try
            {  
                Random random = new Random();//生成随机生成器  
                g.Clear(Color.White);//清空图片背景色              
                for (int i = 0; i < 2; i++)//画图片的背景噪音线
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
                }
                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);
                for (int i = 0; i < 100; i++)//画图片的前景噪音点
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }         
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);//画图片的边框线
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                Response.ClearContent();
                Response.ContentType = "image/Gif";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

    }
}

2、用到验证码的页面

(1)Login_Page.aspx前台

<script language="javascript">//看不清换一个实现
       function change()
        {
            var img = document.getElementById("imgCode");
           img.src=http://www.mamicode.com/img.src+‘?‘;
        }
     </script>

 <tr>
        <td align="right">VerificationCode:</td>
        <td><input type="text" runat="server" id="txtCode" style="width:128px" maxlength="4"  /></td>
        <td>
        <table>
        <tr>
         <td>
         <img alt=‘‘ src="http://www.mamicode.com/CreateVerificationCode_Page.aspx"  id="imgCode"/>
         </td>
         <td>
          <a href="javascript:change();" style="font-size:12px">NotClear?</a>//看不清换一个实现
         </td>
         </tr>

(2)Login_Page.aspx.cs后台

 protected void btnLogin_Click(object sender, EventArgs e)//点击登录验证输入的验证码是否有误
        {
            string checkcode = Session["CheckCode"].ToString();
            if (txtCode.Value.Equals(checkcode, StringComparison.OrdinalIgnoreCase))//判断输入的与验证码是否相等
            {
                Response.Write("<script>alert(‘Verification code input correct!‘)</script>");
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(ClientScript.GetType(), "myscript", "<script>alert(‘Verification code input incorrect!‘)</script>");
            }
        }