asp.net验证码图片生成示例

验证码是一张图片。我们需要在前台代码中写一段<img>,src指向一张页面(ValidateImage.aspx)。

复制代码 代码如下:


<script language="javascript">

function changeImg() {
            $("#imgCheckNo").attr("src", "ValidateImage.aspx?r=" + getRandom(999));
        }
        function getRandom(n) { return Math.floor(Math.random() * n + 1) }
</script>

<div>
<img src="https://www.jb51.net/ValidateImage.aspx">
 <span>看不清?换一张</span>
 </div>
<div>
   <div>验证码:</div>
<div>
<asp:TextBox runat="server" CssClass="tbxCss"></asp:TextBox>
</div>
<div>
<asp:Button runat="server" Text="立即注册" />
</div>

ValidateImage.aspx 用来生产验证码图片,并将验证码的码值保存到cookie中。
代码如下:

复制代码 代码如下:


public partial class ValidateImage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.CreateCheckCodeImage(RndNum());
        }

/// <summary>生成验证码
        /// </summary>
        /// <returns></returns>
        private string RndNum()
        {
            int number;
            char code;
            string checkCode = String.Empty;

System.Random random = new Random();

for (int i = 0; i < 4; i++)
            {
                number = random.Next();
                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('A' + (char)(number % 26));
                checkCode += code.ToString();
            }
            Response.Cookies.Add(new HttpCookie("yzmcode", checkCode));
            return checkCode;
        }

/// <summary>向页面生成验证码Gif图片
        /// </summary>
        /// <param></param>
        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)), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的背景噪音线
                for (int i = 0; i < 25; 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.Silver), x1, y1, x2, y2);
                }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzsfx.html