using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace GxPress.Common.Tools
{
    /// <summary>
    ///     验证码
    /// </summary>
    public static class CaptchaHelper
    {
        /// <summary>
        ///     该方法是将生成的随机数写入图像文件
        /// </summary>
        /// <param name="code">code是一个随机数</param>
        /// <param name="numbers">生成位数（默认4位）</param>
        public static MemoryStream Create(out string code, int numbers = 4)
        {
            code = RandomGenerator.GetString(numbers);

            //生成验证码图片
            var random = new Random();
            //验证码颜色集合
            Color[] c =
            {
                Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan,
                Color.Purple
            };

            //验证码字体集合
            string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };


            //定义图像的大小，生成图像的实例  
            var img = new Bitmap(code.Length * 18, 32);

            var g = Graphics.FromImage(img);

            g.Clear(Color.White); //背景设为白色  

            //在随机位置画背景点  
            for (var i = 0; i < 100; i++)
            {
                var x = random.Next(img.Width);
                var y = random.Next(img.Height);
                g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }

            //验证码绘制在g中  
            for (var i = 0; i < code.Length; i++)
            {
                var cIndex = random.Next(7); //随机颜色索引值 
                var fIndex = random.Next(5); //随机字体索引值 
                var f = new Font(fonts[fIndex], 15, FontStyle.Bold); //字体 
                Brush b = new SolidBrush(c[cIndex]); //颜色  
                var ii = 4;
                if ((i + 1) % 2 == 0) //控制验证码不在同一高度  
                    ii = 2;
                g.DrawString(code.Substring(i, 1), f, b, 3 + i * 12, ii); //绘制一个验证字符  
            }

            var ms = new MemoryStream();
            img.Save(ms, ImageFormat.Jpeg); //将此图像以Png图像文件的格式保存到流中  

            //回收资源  
            g.Dispose();
            img.Dispose();
            return ms;
        }
    }
}