C# 随机验证码

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;

namespace Shop
{
    /// <summary>
    /// 随机产生验证码
    /// </summary>
    public class ValidateCode : System.Web.UI.Page
    {
        //验证码常量信息
        private const string strValidateCodeBound = "abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789";
        //验证码的字体信息
        private static string[] Fonts = new string[] {  "Helvetica","Geneva", "sans-serif","Verdana","Times New Roman","Courier New","Arial"};
       
        /// <summary>
        /// 初始化方法
        /// </summary>
        /// <param name="e"></param>
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// 初始化事件
        /// </summary>
        public void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }

        /// <summary>
        /// 页面加载时的操作
        /// </summary>
        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!IsPostBack)
            {
                //获取需要多少为验证码,6代表需要6位验证码
                string str_ValidateCode = GetRandomString(6);
                //把产生的验证码存放到Session里
                Session["ValidateCode"] = str_ValidateCode;
                //根据验证码生成图片
                CreateImage(str_ValidateCode);
            }
        }

        /// <summary>
        /// 获取随机码
        /// </summary>
        public string GetRandomString(int int_NumberLength)
        {
            string valString = string.Empty;
            Random theRandomNumber = new Random((int)DateTime.Now.Ticks);
            for (int int_index = 0; int_index < int_NumberLength; int_index++)
            {
                valString += strValidateCodeBound[theRandomNumber.Next(strValidateCodeBound.Length - 1)].ToString();
            }
            return valString;
        }

        /// <summary>
        /// 获取每个验证码随机的颜色
        /// </summary>
        private Color GetRandomColor()
        {
            Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
            System.Threading.Thread.Sleep(RandomNum_First.Next(50));
            Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
            int int_Red = RandomNum_First.Next(256);
            int int_Green = RandomNum_Sencond.Next(256);
            int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
            int_Blue = (int_Blue > 255) ? 255 : int_Blue;
            return Color.FromArgb(int_Red, int_Green, int_Blue);
        }

        /// <summary>
        /// 生成图片
        /// </summary>
        private void CreateImage(string str_ValidateCode)
        {
            int int_ImageWidth = str_ValidateCode.Length * 22;
            Random newRandom = new Random();

            Bitmap theBitmap = new Bitmap(int_ImageWidth + 6, 38);
            Graphics theGraphics = Graphics.FromImage(theBitmap);

            theGraphics.Clear(Color.White);

            drawLine(theGraphics, theBitmap, newRandom);
            theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, theBitmap.Width - 1, theBitmap.Height - 1);

            for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
            {
                Matrix X = new Matrix();
                X.Shear((float)newRandom.Next(0, 300) / 1000 - 0.25f, (float)newRandom.Next(0, 100) / 1000 - 0.05f);
                theGraphics.Transform = X;
                string str_char = str_ValidateCode.Substring(int_index, 1);
                System.Drawing.Drawing2D.LinearGradientBrush newBrush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, theBitmap.Width, theBitmap.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                Point thePos = new Point(int_index * 21 + 1 + newRandom.Next(3), 1 + newRandom.Next(13));

                Font theFont = new Font(Fonts[newRandom.Next(Fonts.Length - 1)], newRandom.Next(14, 18), FontStyle.Bold);

                theGraphics.DrawString(str_char, theFont, newBrush, thePos);
            }

            drawPoint(theBitmap, newRandom);

            MemoryStream ms = new MemoryStream();
            theBitmap.Save(ms, ImageFormat.Png);

            Response.ClearContent();
            Response.ContentType = "image/Png";
            Response.BinaryWrite(ms.ToArray());
            theGraphics.Dispose();
            theBitmap.Dispose();
            Response.End();
        }

        /// <summary>
        /// 在验证码图片上画线
        /// </summary>
        private void drawLine(Graphics gfc, Bitmap img, Random ran)
        {
            for (int i = 0; i < 10; i++)
            {
                int x1 = ran.Next(img.Width);
                int y1 = ran.Next(img.Height);
                int x2 = ran.Next(img.Width);
                int y2 = ran.Next(img.Height);
                gfc.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
        }

        /// <summary>
        /// 在验证码图片上画点
        /// </summary>
        private void drawPoint(Bitmap img, Random ran)
        {
            for (int i = 0; i < 30; i++)
            {
                int x = ran.Next(img.Width);
                int y = ran.Next(img.Height);
                img.SetPixel(x, y, Color.FromArgb(ran.Next()));
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值