C# Generate Captcha

2021年7月21日 74点热度 0人点赞 0条评论
内容目录

In ASP.NET Core, the method to generate a verification code along with its code is as follows:

Import ZKWeb.System.Drawing, with the code sample below:

    /// <summary>
    /// Verification Code Service
    /// </summary>
    public class VerificationCode
    {
        // Verification code validity period (seconds)
        private const int ValiditySecond = 60;

        // Width, height, font size
        private const int CodeWidth = 74;
        private const int CodeHeight = 36;
        private const int FontSize = 16;

        // Verification code length
        private const int CodeLength = 4;
        // Number of manic lines and points
        private const int ManicLine = 5;
        private const int ManicPoint = 100;

        // Seed length, that is, index range of the array
        private static readonly int SeedOriginLength = SeedOrigin.Length;

        // Seed
        private static readonly char[] SeedOrigin = new char[]
        {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b','c','d','e','f','g','h','i','j','k','l','m',
            'n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K',
            'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
        };

        // Color list
        private static readonly Color[] Colors = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.DarkBlue };
        // Font list
        private static readonly string[] fonts = { "Times New Roman", "Verdana", "Arial", "Gungsuh" };

        // Verification code cache
        private static readonly ConcurrentDictionary<ulong, CodeCheck> CodeCache = new ConcurrentDictionary<ulong, CodeCheck>();

        /// <summary>
        /// Generate verification code
        /// </summary>
        /// <returns></returns>
        private static string CreateCode(int maxLength)
        {
            char[] code = new char[CodeLength];

            Random random = new Random();

            for (int i = 0; i < CodeLength; i++)
            {
                code[i] = SeedOrigin[random.Next(0, maxLength)];
            }
            return Convert.ToString(code);
        }

        /// <summary>
        /// Get verification code
        /// </summary>
        /// <returns></returns>
        public (string CodeId, string Code, byte[] ImageBytes) GetCode()
        {
            string code = CreateCode(SeedOriginLength);
            ulong codeId = CommonHelper.CreateId();

            Random random = new Random();

            // Create canvas
            Bitmap bitmap = new Bitmap(CodeWidth, CodeHeight);
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.Clear(Color.White);

            // Draw manic lines
            for (int i = 0; i < ManicLine; i++)
            {
                int x1 = random.Next(CodeWidth);
                int y1 = random.Next(CodeHeight);
                int x2 = random.Next(CodeWidth);
                int y2 = random.Next(CodeHeight);
                Color color = Colors[random.Next(Colors.Length)];
                Pen pen = new Pen(color);
                graphics.DrawLine(pen, x1, y1, x2, y2);
            }

            // Draw noise points
            for (int i = 0; i < ManicPoint; i++)
            {
                int x = random.Next(CodeWidth);
                int y = random.Next(CodeHeight);
                Color color = Colors[random.Next(Colors.Length)];
                bitmap.SetPixel(x, y, color);
            }

            // Draw verification code
            for (int i = 0; i < CodeLength; i++)
            {
                string fontStr = fonts[random.Next(fonts.Length)];
                Font font = new Font(fontStr, FontSize);
                Color color = Colors[random.Next(Colors.Length)];
                graphics.DrawString(code[i].ToString(), font, new SolidBrush(color), (float)i * 15 + 2, (float)0);
            }

            try
            {
                MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, ImageFormat.Jpeg);

                CodeCache.TryAdd(codeId, new CodeCheck
                {
                    Id = codeId,
                    DateTime = DateTime.Now,
                    Conent = code
                });
                return (codeId.ToString(), code, stream.ToArray());
            }
            finally
            {
                graphics.Dispose();
                bitmap.Dispose();
            }
        }

        /// <summary>
        /// Check if the user's input verification code is correct
        /// </summary>
        /// <param name="codeId"></param>
        /// <param name="codeText"></param>
        /// <returns></returns>
        public bool Check(string codeId, string codeText)
        {
            if (!ulong.TryParse(codeId, out var id) || string.IsNullOrWhiteSpace(codeText))
                return false;
            // Validity period
            if (!CodeCache.TryGetValue(id, out var value) ||
                (DateTime.Now - value.DateTime).TotalSeconds > ValiditySecond)
                return false;
            // Check if the verification code is correct, ignoring case
            if (!value.Conent.Equals(codeText, StringComparison.OrdinalIgnoreCase))
                return false;

            return true;
        }

        private class CodeCheck
        {
            /// <summary>
            /// Verification Code Id
            /// </summary>
            public ulong Id { get; set; }

            /// <summary>
            /// Verification Code Generation Time
            /// </summary>
            public DateTime DateTime { get; set; }

            /// <summary>
            /// Verification Code Id
            /// </summary>
            public string Conent { get; set; }
        }
    }

痴者工良

高级程序员劝退师

文章评论