using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
    private const double PI = 3.1415926535897932384626433832795;
    private const double PI2 = 6.283185307179586476925286766559;

    protected void Page_Load(object sender, EventArgs e)
    {
        base.Response.Cache.SetNoStore();
        Bitmap image = new Bitmap(70, 20);//宽高
        Graphics graphics = Graphics.FromImage(image);
        Color[] colorArray2 = new Color[] { Color.AliceBlue, Color.Aqua, Color.Black, Color.Brown, Color.DarkRed, Color.SkyBlue, Color.Silver, Color.Tan, Color.Violet, Color.SpringGreen };
        try
        {
            //生成随机生成器
            Random random = new Random();
            //清空图片背景色
            graphics.Clear(GetRandomColor1());

            //画图片的背景噪音线
            for (int i = 0; i < 10; i++)// 随机产生12条干扰线,使图象中的认证码不易被其它程序探测到
            {
                int num2 = random.Next(image.Width);
                int num3 = random.Next(image.Width);
                int num4 = random.Next(image.Height - 2);
                int num5 = random.Next(image.Height + 2);
                graphics.DrawLine(new Pen(Color.Silver), num2, num4, num3, num5);
            }

            string[] strArray = "1,2,3,4,5,6,7,8,9".Split(new char[] { ',' });
            string s = string.Empty;

            //画图片的前景噪音点
            for (int j = 0; j < 4; j++)//4位认证码
            {
                s = s + strArray[random.Next(strArray.Length)];
            }
            //认证码字体
            Font font = new Font("Fixedsys", 11f, FontStyle.Bold);


            //画图片的边框线
            LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(random.Next(image.Width), random.Next(image.Height), image.Width, image.Height), GetRandomColor(), Color.Red, 1.2f, true);

            graphics.DrawString(s, font, brush, (float)random.Next(image.Width - 40), (float)random.Next(image.Height - 20));

            //验证码
            graphics.DrawRectangle(new Pen(colorArray2[random.Next(colorArray2.Length)]), 0, 0, image.Width - 1, image.Height - 1);

            //图片扭曲
            image = TwistImage(image, true, -4, 3);

            MemoryStream stream = new MemoryStream();
            image.Save(stream, ImageFormat.Gif);
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ContentType = "image/Gif";
            HttpContext.Current.Response.BinaryWrite(stream.ToArray());
            this.Session["ValidateCode"] = s.ToLower();
        }
        finally
        {
            graphics.Dispose();
            image.Dispose();
        }

    }

    /// <summary>
    /// 正弦曲线Wave扭曲图片
    /// </summary>
    /// <param name="srcBmp">图片路径</param>
    /// <param name="bXDir">如果扭曲则选择为True</param>
    /// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
    /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
    /// <returns></returns>
    public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
    {
        System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);

        // 将位图背景填充为白色
        System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);

        graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);

        graph.Dispose();

        double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

        for (int i = 0; i < destBmp.Width; i++)
        {
            for (int j = 0; j < destBmp.Height; j++)
            {
                double dx = 0;

                dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;

                dx += dPhase;

                double dy = Math.Sin(dx);

                // 取得当前点的颜色
                int nOldX = 0, nOldY = 0;

                nOldX = bXDir ? i + (int)(dy * dMultValue) : i;

                nOldY = bXDir ? j : j + (int)(dy * dMultValue);

                System.Drawing.Color color = srcBmp.GetPixel(i, j);
                if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height)
                {
                    destBmp.SetPixel(nOldX, nOldY, color);
                }
            }
        }
        return destBmp;
    }

    //随即文字颜色
    public 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(50);//红色
        int int_Green = RandomNum_Sencond.Next(50);//绿色
        int int_Blue = (int_Red + int_Green > 20) ? 0 : 100 - int_Red - int_Green;
        int_Blue = (int_Blue > 255) ? 255 : int_Blue;//蓝色
        return Color.FromArgb(int_Red, int_Green, int_Blue);
    }

    //随即背景颜色
    public Color GetRandomColor1()
    {
        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(255);//红色
        int int_Green = RandomNum_Sencond.Next(255);//绿色
        int int_Blue = (int_Red + int_Green > 255) ? 0 : 450 - int_Red - int_Green;
        int_Blue = (int_Blue > 255) ? 255 : int_Blue;//蓝色
        return Color.FromArgb(int_Red, int_Green, int_Blue);
    }
}