浏览代码

Библиотека для генерации капчи готова

MeseryGG 7 月之前
父节点
当前提交
93e6fea565

+ 11 - 0
CapchaLibrary/CapchaData.cs

@@ -0,0 +1,11 @@
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace CapchaLibrary
+{
+    public record class CapchaData(Bitmap CapchaImage, string Code);
+}

+ 123 - 0
CapchaLibrary/CapchaGenerator.cs

@@ -0,0 +1,123 @@
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace CapchaLibrary
+{
+    public class CapchaGenerator
+    {
+
+        /// <summary>
+        /// Базовый конструктор, создающий генератор капчи по умолчанию
+        /// </summary>
+        public CapchaGenerator()
+        {
+            ValidCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+            SymbolsCount = 6;
+            NoiseCount = 25;
+            random = new Random(DateTime.Now.Microsecond);
+        }
+
+        /// <summary>
+        /// Конструктор генератора, позволяющий задавать используемые при создании капчи символы, количество символов в капче и количество шума
+        /// </summary>
+        /// <param name="validCharacters">Используемые при создании символы</param>
+        /// <param name="symbolsCount">Количество символов в капче</param>
+        public CapchaGenerator(string validCharacters, int symbolsCount, int noiseCount) 
+        {
+            ValidCharacters = validCharacters;
+            SymbolsCount = symbolsCount;
+            NoiseCount = noiseCount;
+            random = new Random(DateTime.Now.Microsecond);
+        }
+
+
+        /// <summary>
+        /// Строка состоящая из символов, использующихся при создании капчи
+        /// </summary>
+        public string ValidCharacters { get; init; }
+
+        /// <summary>
+        /// Количество символов в капче
+        /// </summary>
+        public int SymbolsCount { get; init; }
+
+        /// <summary>
+        /// Количество шума на капче
+        /// </summary>
+        public int NoiseCount {  get; init; }
+
+
+        /// <summary>
+        /// Метод генерации капчи
+        /// </summary>
+        /// <returns>Данные по сгенерированной капче</returns>
+        public CapchaData GenerateCapcha()
+        {
+            string capchaCode = GenerateCapchaCode();
+            Bitmap capcha = GenerateCapcha(capchaCode);
+            return new CapchaData(capcha, capchaCode);
+        }
+
+
+        private readonly Dictionary<int,(Color, Brush)> CapchaColors = new Dictionary<int,(Color, Brush)>() 
+        {
+            { 0, (Color.Aquamarine, Brushes.Aqua) },
+            { 1, (Color.PapayaWhip, Brushes.Pink) },
+            { 2, (Color.Coral, Brushes.IndianRed) },
+        };
+
+        private readonly Random random;
+
+
+        /// <summary>
+        /// Метод генерации кода капчи
+        /// </summary>
+        /// <returns>Код капчи</returns>
+        private string GenerateCapchaCode() =>
+            new string(Enumerable.Repeat(ValidCharacters, SymbolsCount)
+                .Select(s => s[random.Next(s.Length)])
+                .ToArray());
+
+        /// <summary>
+        /// Метод генерации изображения капчи
+        /// </summary>
+        /// <param name="capchaCode">Код капчи</param>
+        /// <returns>Изображение капчи</returns>
+        private Bitmap GenerateCapcha(string capchaCode)
+        {
+            Bitmap capcha = new(2560, 1440);
+            (Color, Brush) colors = GetRandomCapchaColor();
+            using (Graphics graphics = Graphics.FromImage(capcha))
+            {
+                graphics.Clear(colors.Item1);
+                int SymbolX = 150;
+                int SymbolY = 650;
+                foreach (char symbol in capchaCode)
+                {
+                    int NextSymbolY = SymbolY + (random.Next(0, 600) - 600);
+                    graphics.DrawString(symbol.ToString(), new Font("Comic Sans MS", 320, FontStyle.Bold), colors.Item2, new PointF(SymbolX, NextSymbolY));
+                    SymbolX += 360;
+                }
+                for(int noiseCounter = 0; noiseCounter < NoiseCount; noiseCounter++)
+                {
+                    graphics.DrawLine(new Pen(Brushes.DarkBlue, 5)
+                        , new Point(random.Next(0, 2560), random.Next(0, 1440))
+                        , new Point(random.Next(0, 2560), random.Next(0, 1440)));
+                }
+            }
+            return capcha;
+        }
+
+        private (Color, Brush) GetRandomCapchaColor()
+        {
+            (Color, Brush) brush;
+            CapchaColors.TryGetValue(random.Next(0,3), out brush);
+            return brush;
+        }
+    }
+}

+ 13 - 0
CapchaLibrary/CapchaLibrary.csproj

@@ -0,0 +1,13 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <TargetFramework>net7.0</TargetFramework>
+    <ImplicitUsings>enable</ImplicitUsings>
+    <Nullable>enable</Nullable>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <PackageReference Include="System.Drawing.Common" Version="6.0.0" />
+  </ItemGroup>
+
+</Project>

+ 7 - 1
OOO_WriteAndClear.sln

@@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
 # Visual Studio Version 17
 VisualStudioVersion = 17.6.33829.357
 MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OOO_WriteAndClear", "OOO_WriteAndClear\OOO_WriteAndClear.csproj", "{7A650562-31AE-4C9B-AFA1-7F755C21486B}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OOO_WriteAndClear", "OOO_WriteAndClear\OOO_WriteAndClear.csproj", "{7A650562-31AE-4C9B-AFA1-7F755C21486B}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CapchaLibrary", "CapchaLibrary\CapchaLibrary.csproj", "{35249A41-301E-4AA6-9C92-0F440DEF2F0A}"
 EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -15,6 +17,10 @@ Global
 		{7A650562-31AE-4C9B-AFA1-7F755C21486B}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{7A650562-31AE-4C9B-AFA1-7F755C21486B}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{7A650562-31AE-4C9B-AFA1-7F755C21486B}.Release|Any CPU.Build.0 = Release|Any CPU
+		{35249A41-301E-4AA6-9C92-0F440DEF2F0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{35249A41-301E-4AA6-9C92-0F440DEF2F0A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{35249A41-301E-4AA6-9C92-0F440DEF2F0A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{35249A41-301E-4AA6-9C92-0F440DEF2F0A}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 6 - 1
OOO_WriteAndClear/App.xaml.cs

@@ -1,4 +1,5 @@
-using System.Configuration;
+using CapchaLibrary;
+using System.Configuration;
 using System.Data;
 using System.Windows;
 
@@ -9,5 +10,9 @@ namespace OOO_WriteAndClear
     /// </summary>
     public partial class App : Application
     {
+        public App() 
+        {
+            new CapchaGenerator().GenerateCapcha();
+        }
     }
 }

+ 1 - 1
OOO_WriteAndClear/MVP/Models/AuthorizationUserControlModel/AuthorizationUserControlModel.cs → OOO_WriteAndClear/MVP/Models/AuthorizationUserControlModel.cs

@@ -11,7 +11,7 @@ namespace OOO_WriteAndClear.MVP.Models
 {
     public class AuthorizationUserControlModel : IAuthorizationContract.IModel
     {
-        public AuthorizationUserControlModel() 
+        public AuthorizationUserControlModel()
         {
 
         }

+ 0 - 40
OOO_WriteAndClear/MVP/Models/AuthorizationUserControlModel/CapchaGenerator.cs

@@ -1,40 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Drawing;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace OOO_WriteAndClear.MVP.Models.AuthorizationUserControlModel
-{
-    public class CapchaGenerator
-    {
-        public const string AvableChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
-
-
-        public CapchaGenerator(int symbolsCount) 
-        {
-            _symbolsCount = symbolsCount;
-        }
-
-
-        public void GenerateCapcha()
-        {
-            _captchaCode = GenerateCaptchaCode();
-
-        }
-
-
-        private string _captchaCode;
-
-        private int _symbolsCount;
-
-
-        private string GenerateCaptchaCode()
-        {
-            Random random = new Random();
-            return new string(Enumerable.Repeat(AvableChars, _symbolsCount)
-                .Select(s => s[random.Next(s.Length)]).ToArray());
-        }
-    }
-}

+ 4 - 0
OOO_WriteAndClear/OOO_WriteAndClear.csproj

@@ -93,4 +93,8 @@
     </Content>
   </ItemGroup>
 
+  <ItemGroup>
+    <ProjectReference Include="..\CapchaLibrary\CapchaLibrary.csproj" />
+  </ItemGroup>
+
 </Project>