ASP.NET 实现验证码以及刷新验证码的小例子


/// <summary>
    /// 生成验证码图片,保存session名称VerificationCode
    /// </summary>
    public static void CreateVerificationCode()
    {
        int number;
        string checkCode = string.Empty;

//随机数种子
        Random randoms = new Random();

for (int i = 0; i < 4; i++) //校验码长度为4
        {
            //随机的整数
            number = randoms.Next();

//字符从0-9,A-Z中随机产生,对应的ASCII码分别为
            //48-57,65-90
            number = number % 36;
            if (number < 10)
            {
                number += 48;
            }
            else
            {
                number += 55;
            }
            checkCode += ((char)number).ToString();
        }

//在session中保存校验码
        System.Web.HttpContext.Current.Session["VerificationCode"] = checkCode;

//若校验码为空,则直接返回
        if (checkCode == null || checkCode.Trim() == String.Empty)
        {
            return;
        }
        //根据校验码的长度确定输出图片的长度
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(55, 20);//(int)Math.Ceiling(Convert.ToDouble(checkCode.Length * 15))
        //创建Graphics对象
        Graphics g = Graphics.FromImage(image);
        try
        {
            //生成随机数种子
            Random random = new Random();
            //清空图片背景色
            g.Clear(Color.White);
            //画图片的背景噪音线 10条
            //---------------------------------------------------
            for (int i = 0; i < 10; i++)
            {
                //噪音线起点坐标(x1,y1),终点坐标(x2,y2)
                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);
            }
            //---------------------------------------------------
            //Brush b = Brushes.Silver;
            //g.FillRectangle(b, 0, 0, image.Width, image.Height);
            //---------------------以上两种任选其一------------------------------
            //输出图片中校验码的字体: 12号Arial,粗斜体
            Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));

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

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