├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── winforms-image-processor.sln └── winforms-image-processor ├── CacheManager └── CacheManager.cs ├── DrawTools ├── Capsule.cs ├── ClippedPolygon.cs ├── Clipping.cs ├── ColorInterpolator.cs ├── Fill.cs ├── Filler.cs ├── MidPointCircle.cs ├── MidPointLine.cs ├── Polygon.cs ├── Rectangle.cs └── Shape.cs ├── Filters ├── BitmapExtension.cs ├── ColorspaceTools.cs ├── Constants.cs ├── FilterManager.cs ├── Kernel.cs └── OctreeTools.cs ├── Forms ├── App.config ├── ConstantsEditor.Designer.cs ├── ConstantsEditor.cs ├── ConstantsEditor.resx ├── DrawForm.Designer.cs ├── DrawForm.cs ├── DrawForm.resx ├── FillMenu.Designer.cs ├── FillMenu.cs ├── FillMenu.resx ├── ImageProcessorForm.Designer.cs ├── ImageProcessorForm.cs ├── ImageProcessorForm.resx ├── KernelEditor.Designer.cs ├── KernelEditor.cs ├── KernelEditor.resx ├── Program.cs ├── YBRColorspaceDisplay.Designer.cs ├── YBRColorspaceDisplay.cs └── YBRColorspaceDisplay.resx ├── Properties ├── AssemblyInfo.cs ├── Resources.Designer.cs ├── Resources.resx ├── Settings.Designer.cs └── Settings.settings ├── SaveTools └── ShapeSerializer.cs ├── app.config └── winforms-image-processor.csproj /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Julian Szachowicz 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Image processing in C# Winforms 2 | 3 | This project aims to recreat various image/bitmap processing methods and algorithms in a C# Winforms environment. 4 | 5 | ## Image processing features 6 | 7 | The following options are available for image processing. 8 | 9 | ### Image processor window 10 | 11 | * Displays the original and modified image side by side 12 | * You can directly copy from the modified image context menu 13 | * You can select the image view mode from "fit" and "view original size" 14 | 15 |

16 | 17 |

18 | 19 | ### Filters 20 | 21 | * You can apply a wide variety of functional as well as convolution filters 22 | * You can add as many layers as you like 23 | * Order of applying filters is taken into account 24 | * A caching system stores each bitmap for a given order of filter layers 25 | 26 |

27 | 28 |

29 | 30 | ### Custom convolution kernel 31 | 32 | * Adds a custom kernel to the filters list 33 | * You can edit the kernel setup in a the Edit Kernel window 34 | * You can choose row and column count, kernel divisor (by default set automatically to sum of all cells), value offset and anchor point (wrt. applied cell) 35 | 36 |

37 | 38 |

39 | 40 | ### Filter options window 41 | 42 | * Changes the values used in certain filters 43 | * Reapplies all current layers 44 | 45 |

46 | 47 |

48 | 49 | ### YCbCr colorspace split 50 | 51 | * Displays the current (modified) image [YCbCr colorspace](https://en.wikipedia.org/wiki/YCbCr) split 52 | 53 |

54 | 55 |

56 | 57 | ## Bitmap creation features 58 | 59 | The following options are available for bitmap creation (accessible via the Drawing window) 60 | 61 | ### Drawing window 62 | 63 | * A seperate window for all your bitmap creation needs 64 | * Allows saving and opening states (stored in serialized binary files) 65 | 66 |

67 | 68 |

69 | 70 | ### Shapes 71 | 72 | * Various shapes can be created simply by clicking 73 | * These are vector object shapes, stored and treated as objects (ie. circle has an origin point and a radius) 74 | * All shapes can be moved, redrawn or removed in the shapes menu (color and thickness taken into account while redrawing) 75 | * Polygons may be clipped 76 | 77 |

78 | 79 |

80 | 81 | ### Additional setup 82 | 83 | * Background color may be changed 84 | * Anti-aliasing may be turned on and off for shapes using midpoint lines 85 | * The clipping boundary may be displayed 86 | 87 |

88 | 89 |

90 | 91 | ### Filling 92 | 93 | * Point-based flood fill is available (and stored as separate object) 94 | * Polygons may be filled with specific colors or tiled images 95 | 96 |

97 | 98 |

99 | 100 | ## Final note 101 | 102 | If for some darn reason good ol' Microsoft Paint ain't satisfying all your image dillydallying needs, head on down to Joe's Peppercot Farms n' try out that dandy release in the right-as-the-Lord-himself -hand menu. God bless 🤠 103 | -------------------------------------------------------------------------------- /winforms-image-processor.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.489 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "winforms-image-processor", "winforms-image-processor\winforms-image-processor.csproj", "{11F06003-A488-40FF-BF13-FF7114F9D866}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {11F06003-A488-40FF-BF13-FF7114F9D866}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {11F06003-A488-40FF-BF13-FF7114F9D866}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {11F06003-A488-40FF-BF13-FF7114F9D866}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {11F06003-A488-40FF-BF13-FF7114F9D866}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {69161561-A82C-416A-A3D0-9CBAAE32F87D} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /winforms-image-processor/CacheManager/CacheManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Runtime.Serialization; 7 | using System.Runtime.Serialization.Formatters.Binary; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using System.Windows.Forms; 11 | 12 | namespace winforms_image_processor 13 | { 14 | /// 15 | /// The CacheManager Class is responsible for storing caches of image filter states. 16 | /// This greatly saves processing time, but increases load on memory. 17 | /// 18 | static class CacheManager 19 | { 20 | public static List filterState; 21 | public static Dictionary, Bitmap> cachedFilterStates = null; 22 | 23 | public static void InitializeWithOriginal(Bitmap bmp) 24 | { 25 | filterState = new List(); 26 | 27 | cachedFilterStates = new Dictionary, Bitmap>(new StringListEqComparer()) 28 | { 29 | { new List(), DeepCopy(bmp)} 30 | }; 31 | } 32 | 33 | public static void UpdateFilterState(string filter, bool newChecked) 34 | { 35 | if (newChecked) 36 | filterState.Add(filter); 37 | else 38 | filterState.Remove(filter); 39 | } 40 | 41 | public static void ResetCache(Bitmap bmp) 42 | { 43 | cachedFilterStates.Clear(); 44 | 45 | cachedFilterStates = new Dictionary, Bitmap>(new StringListEqComparer()) 46 | { 47 | { new List(), DeepCopy(bmp)} 48 | }; 49 | } 50 | 51 | public static Bitmap GetBitmapForFilterState() => cachedFilterStates.ContainsKey(filterState) ? cachedFilterStates[filterState] : null; 52 | 53 | public static void SetBitmapForFilterState(Bitmap bmp) => cachedFilterStates[filterState] = DeepCopy(bmp); 54 | 55 | public static Bitmap GetOriginalImage() => cachedFilterStates[new List()]; 56 | 57 | public static T DeepCopy(T source) 58 | // Sources used 59 | // Deepcopy w/ stream: https://stackoverflow.com/questions/43039099/creating-a-completely-new-copy-of-bitmap-from-a-bitmap-in-c-sharp/43042865#43042865 60 | { 61 | if (!typeof(T).IsSerializable) 62 | { 63 | throw new ArgumentException("The type must be serializable.", "source"); 64 | } 65 | 66 | if (Object.ReferenceEquals(source, null)) 67 | { 68 | return default(T); 69 | } 70 | 71 | IFormatter formatter = new BinaryFormatter(); 72 | Stream stream = new MemoryStream(); 73 | using (stream) 74 | { 75 | formatter.Serialize(stream, source); 76 | stream.Seek(0, SeekOrigin.Begin); 77 | return (T)formatter.Deserialize(stream); 78 | } 79 | } 80 | } 81 | 82 | public class StringListEqComparer : IEqualityComparer> 83 | // Sources used 84 | // Custom compare: https://stackoverflow.com/questions/14663168/an-integer-array-as-a-key-for-dictionary 85 | { 86 | public bool Equals(List x, List y) 87 | { 88 | if (x.Count != y.Count) 89 | { 90 | return false; 91 | } 92 | for (int i = 0; i < x.Count; i++) 93 | { 94 | if (x[i] != y[i]) 95 | { 96 | return false; 97 | } 98 | } 99 | return true; 100 | } 101 | 102 | public int GetHashCode(List obj) 103 | { 104 | int result = 17; 105 | for (int i = 0; i < obj.Count; i++) 106 | { 107 | unchecked 108 | { 109 | result = result * 23 + obj[i].GetHashCode(); 110 | } 111 | } 112 | return result; 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/Capsule.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace winforms_image_processor 9 | { 10 | [Serializable] 11 | class Capsule : Shape 12 | { 13 | Point? startPoint = null; 14 | Point? endPoint = null; 15 | int? radius = null; 16 | 17 | public Capsule(Color color) : base(color) 18 | { shapeType = DrawingShape.CAPS; } 19 | 20 | public override int AddPoint(Point point) 21 | { 22 | if (startPoint == null) 23 | startPoint = point; 24 | else if (endPoint == null) 25 | endPoint = point; 26 | else if (radius == null) 27 | { 28 | radius = (int)Math.Sqrt(Math.Pow(point.X - endPoint.Value.X, 2) + Math.Pow(point.Y - endPoint.Value.Y, 2)); 29 | return 1; 30 | } 31 | return 0; 32 | } 33 | 34 | public override List GetPixels(params object[] param) 35 | { 36 | var points = new List(); 37 | 38 | var lowerStart = getAuxPoint(startPoint.Value, endPoint.Value, 1, out double angle1); 39 | var lowerEnd = getAuxPoint(endPoint.Value, startPoint.Value, -1, out double angle2); 40 | 41 | var upperEnd = getAuxPoint(endPoint.Value, startPoint.Value, 1, out double angle3); 42 | var upperStart = getAuxPoint(startPoint.Value, endPoint.Value, -1, out double angle4); 43 | 44 | points.AddRange(new MidPointCircle(shapeColor, startPoint.Value, radius.Value).getSemiCircle(angle1 + Math.PI/2)); 45 | points.AddRange(new MidPointCircle(shapeColor, endPoint.Value, radius.Value).getSemiCircle(angle3 + Math.PI/2)); 46 | 47 | points.AddRange(new MidPointLine(shapeColor, 1, lowerStart, lowerEnd).GetPixels()); 48 | points.AddRange(new MidPointLine(shapeColor, 1, upperStart, upperEnd).GetPixels()); 49 | 50 | return points; 51 | } 52 | 53 | Point getAuxPoint(Point start, Point end, int side, out double a) 54 | { 55 | int ABY = end.Y - start.Y; 56 | int ABX = end.X - start.X; 57 | 58 | a = Math.Atan2(end.Y - start.Y, end.X - start.X) + side * 90.0 * Math.PI / 180.0; // sign depends on your 59 | 60 | var Len = Math.Sqrt(ABY * ABY + ABX * ABX); 61 | var CX = (int)(startPoint.Value.X - radius * ABY / Len).Value; 62 | var CY = (int)(startPoint.Value.Y + radius * ABX / Len).Value; 63 | 64 | return new Point((int)(start.X + radius * Math.Cos(a)).Value, (int)(start.Y + radius * Math.Sin(a)).Value); 65 | } 66 | 67 | public override void MovePoints(Point displacement) 68 | { 69 | startPoint = startPoint.Value + (Size)displacement; 70 | endPoint = endPoint.Value + (Size)displacement; 71 | } 72 | 73 | public override string ToString() 74 | { 75 | return "Capsule"; 76 | } 77 | 78 | public override string howToDraw() 79 | { 80 | return "Click point 1, point 2 and radius."; 81 | } 82 | 83 | public override List GetPixelsAA(Bitmap bmp) 84 | { 85 | throw new NotImplementedException(); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/ClippedPolygon.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace winforms_image_processor 9 | { 10 | [Serializable] 11 | class ClippedPolygon : Polygon 12 | { 13 | Rectangle boundingRect = new Rectangle(Color.Transparent, 0); 14 | 15 | public ClippedPolygon(Color col, int thicc) : base(col, thicc) { } 16 | 17 | public ClippedPolygon(Polygon P) : base(P.shapeColor, P.thickness) 18 | { 19 | shapeType = DrawingShape.CPOLY; 20 | supportsAA = true; 21 | points = P.points; 22 | } 23 | 24 | public override List GetPixels(params object[] param) 25 | { 26 | var pixels = new List(); 27 | 28 | Clipping clipper = new Clipping(); 29 | clipper.SetBoundingRectangle(boundingRect); 30 | 31 | if (filler != null) 32 | pixels.AddRange(filler.FillPoints(boundingRect)); 33 | 34 | Color ofLine = shapeColor; 35 | if (param.Length == 2 && param[1] is Color) 36 | ofLine = Color.FromArgb(((Color)param[1]).ToArgb() ^ 0xffffff); 37 | 38 | for (int i = 0; i <= points.Count - 2; i++) 39 | pixels.AddRange(new MidPointLine(ofLine, thickness + 3, points[i], points[i + 1], clipper).GetPixels()); 40 | 41 | if (param.Length > 0 && (bool)param[0]) 42 | pixels.AddRange(boundingRect.GetPixels()); 43 | 44 | return pixels; 45 | } 46 | 47 | public override List GetPixelsAA(Bitmap bmp) 48 | { 49 | var pixels = new List(); 50 | 51 | Clipping clipper = new Clipping(); 52 | clipper.SetBoundingRectangle(boundingRect); 53 | 54 | if (filler != null) 55 | pixels.AddRange(filler.FillPoints(boundingRect)); 56 | 57 | for (int i = 0; i <= points.Count - 2; i++) 58 | pixels.AddRange(new MidPointLine(shapeColor, thickness + 3, points[i], points[i + 1], clipper).GetPixelsAA(bmp)); 59 | 60 | return pixels; 61 | } 62 | 63 | public void SetBoundingRect(Rectangle rect) 64 | { 65 | boundingRect = rect; 66 | 67 | } 68 | 69 | public override string howToDraw() 70 | { 71 | return "Click each point and click on first to finish."; 72 | } 73 | 74 | public override string ToString() 75 | { 76 | return "Clipped Polygon"; 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/Clipping.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace winforms_image_processor 9 | { 10 | public struct Line 11 | { 12 | public Point Start; 13 | public Point End; 14 | 15 | public Line(Point s, Point e) 16 | { 17 | End = e; 18 | Start = s; 19 | } 20 | 21 | public override string ToString() 22 | { 23 | return $"{Start.ToString()} && {End.ToString()}"; 24 | } 25 | } 26 | 27 | [Serializable] 28 | class Clipping 29 | { 30 | // https://pastebin.com/NA01gacf 31 | 32 | private Point _clipMin, _clipMax; 33 | 34 | public IEnumerable GetBoundingPolygon() 35 | { 36 | yield return _clipMin; 37 | yield return new Point(_clipMax.X, _clipMin.Y); 38 | yield return _clipMax; 39 | yield return new Point(_clipMin.X, _clipMax.Y); 40 | } 41 | 42 | public void SetBoundingRectangle(Rectangle rect) 43 | { 44 | _clipMin = rect.GetCorner(3); 45 | _clipMax = rect.GetCorner(1); 46 | } 47 | 48 | private delegate bool ClippingHandler(float p, float q); 49 | 50 | public bool ClipLine(ref Line line) 51 | { 52 | Point P = line.End - (Size)line.Start; 53 | float tMinimum = 0, tMaximum = 1; 54 | 55 | ClippingHandler pqClip = delegate (float directedProjection, 56 | float directedDistance) 57 | { 58 | if (directedProjection == 0) 59 | { 60 | if (directedDistance < 0) 61 | return false; 62 | } 63 | else 64 | { 65 | float amount = directedDistance / directedProjection; 66 | if (directedProjection < 0) 67 | { 68 | if (amount > tMaximum) 69 | return false; 70 | else if (amount > tMinimum) 71 | tMinimum = amount; 72 | } 73 | else 74 | { 75 | if (amount < tMinimum) 76 | return false; 77 | else if (amount < tMaximum) 78 | tMaximum = amount; 79 | } 80 | } 81 | return true; 82 | }; 83 | 84 | if (pqClip(-P.X, line.Start.X - _clipMin.X)) 85 | { 86 | if (pqClip(P.X, _clipMax.X - line.Start.X)) 87 | { 88 | if (pqClip(-P.Y, line.Start.Y - _clipMin.Y)) 89 | { 90 | if (pqClip(P.Y, _clipMax.Y - line.Start.Y)) 91 | { 92 | if (tMaximum < 1) 93 | { 94 | line.End.X = (int)(line.Start.X + tMaximum * P.X); 95 | line.End.Y = (int)(line.Start.Y + tMaximum * P.Y); 96 | } 97 | if (tMinimum > 0) 98 | { 99 | line.Start.X = (int)(line.Start.X + tMinimum * P.X); 100 | line.Start.Y = (int)(line.Start.Y + tMinimum * P.Y); 101 | } 102 | return true; 103 | } 104 | } 105 | } 106 | } 107 | return false; 108 | } 109 | 110 | //public bool ClipLine(ref MidPointLine line) 111 | //{ 112 | // Point P = line.endPoint.Value - (Size)line.startPoint.Value; 113 | // float tMinimum = 0, tMaximum = 1; 114 | 115 | // ClippingHandler pqClip = delegate (float directedProjection, 116 | // float directedDistance) 117 | // { 118 | // if (directedProjection == 0) 119 | // { 120 | // if (directedDistance < 0) 121 | // return false; 122 | // } 123 | // else 124 | // { 125 | // float amount = directedDistance / directedProjection; 126 | // if (directedProjection < 0) 127 | // { 128 | // if (amount > tMaximum) 129 | // return false; 130 | // else if (amount > tMinimum) 131 | // tMinimum = amount; 132 | // } 133 | // else 134 | // { 135 | // if (amount < tMinimum) 136 | // return false; 137 | // else if (amount < tMaximum) 138 | // tMaximum = amount; 139 | // } 140 | // } 141 | // return true; 142 | // }; 143 | 144 | // if (pqClip(-P.X, line.startPoint.Value.X - _clipMin.X)) 145 | // { 146 | // if (pqClip(P.X, _clipMax.X - line.startPoint.Value.X)) 147 | // { 148 | // if (pqClip(-P.Y, line.startPoint.Value.Y - _clipMin.Y)) 149 | // { 150 | // if (pqClip(P.Y, _clipMax.Y - line.startPoint.Value.Y)) 151 | // { 152 | // if (tMaximum < 1) 153 | // line.endPoint = new Point((int)(line.startPoint.Value.X + tMaximum * P.X), (int)(line.startPoint.Value.Y + tMaximum * P.Y)); 154 | // if (tMinimum > 0) 155 | // line.startPoint = new Point((int)(line.startPoint.Value.X + tMinimum * P.X), (int)(line.startPoint.Value.Y + tMinimum * P.Y)); 156 | // return true; 157 | // } 158 | // } 159 | // } 160 | // } 161 | // return false; 162 | //} 163 | 164 | public override string ToString() 165 | { 166 | return "Liang-Barsky algorithm"; 167 | } 168 | 169 | // This code was implemented by Grishul Eugeny as part of preparation 170 | // to exam in ITMO university 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/ColorInterpolator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace winforms_image_processor 9 | { 10 | static public class ColorInterpolator 11 | // Source https://stackoverflow.com/questions/1236683/color-interpolation-between-3-colors-in-net 12 | { 13 | delegate byte ComponentSelector(Color color); 14 | static ComponentSelector _redSelector = color => color.R; 15 | static ComponentSelector _greenSelector = color => color.G; 16 | static ComponentSelector _blueSelector = color => color.B; 17 | 18 | public static Color InterpolateBetween( 19 | Color endPoint1, 20 | Color endPoint2, 21 | double lambda) 22 | { 23 | if (lambda < 0 || lambda > 1) 24 | { 25 | throw new ArgumentOutOfRangeException("lambda"); 26 | } 27 | Color color = Color.FromArgb( 28 | InterpolateComponent(endPoint1, endPoint2, lambda, _redSelector), 29 | InterpolateComponent(endPoint1, endPoint2, lambda, _greenSelector), 30 | InterpolateComponent(endPoint1, endPoint2, lambda, _blueSelector) 31 | ); 32 | 33 | return color; 34 | } 35 | 36 | static byte InterpolateComponent( 37 | Color endPoint1, 38 | Color endPoint2, 39 | double lambda, 40 | ComponentSelector selector) 41 | { 42 | return (byte)(selector(endPoint1) 43 | + (selector(endPoint2) - selector(endPoint1)) * lambda); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/Fill.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace winforms_image_processor 9 | { 10 | [Serializable] 11 | class Fill : Shape 12 | { 13 | public Point seedPoint; 14 | 15 | public Fill(Color col, Point p) : base(col) 16 | { 17 | shapeType = DrawingShape.FILL; 18 | seedPoint = p; 19 | } 20 | 21 | public override int AddPoint(Point point) 22 | { 23 | throw new NotImplementedException(); 24 | } 25 | 26 | public override List GetPixels(params object[] param) 27 | { 28 | throw new NotImplementedException(); 29 | } 30 | 31 | public override List GetPixelsAA(Bitmap bmp) 32 | { 33 | throw new NotImplementedException(); 34 | } 35 | 36 | public override string howToDraw() 37 | { 38 | throw new NotImplementedException(); 39 | } 40 | 41 | public override void MovePoints(Point displacement) 42 | { 43 | seedPoint += (Size)displacement; 44 | } 45 | 46 | public override string ToString() 47 | { 48 | return "Filled region"; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/Filler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | using System.Drawing; 6 | using System.Dynamic; 7 | using System.Linq; 8 | using System.Security.Cryptography.X509Certificates; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | using System.Windows; 12 | using System.Windows.Forms; 13 | using Point = System.Drawing.Point; 14 | 15 | namespace winforms_image_processor 16 | { 17 | [Serializable] 18 | public struct ActiveEdgeTableEntry 19 | { 20 | public double yMax; 21 | public double yMin; 22 | public double mInv; 23 | public double xOfMin; 24 | public double xOfMax; 25 | 26 | public ActiveEdgeTableEntry(Point start, Point end) 27 | { 28 | Point lower = start.Y > end.Y ? end : start; 29 | Point higher = start.Y > end.Y ? start : end; 30 | 31 | yMax = higher.Y; 32 | yMin = lower.Y; 33 | xOfMax = higher.X; 34 | xOfMin = lower.X; 35 | mInv = (xOfMax - xOfMin) / (yMax - yMin); 36 | } 37 | 38 | public ActiveEdgeTableEntry(ActiveEdgeTableEntry aete) 39 | { 40 | yMax = aete.yMax; 41 | yMin = aete.yMin; 42 | xOfMax = aete.xOfMax; 43 | xOfMin = aete.xOfMin + aete.mInv; 44 | mInv = aete.mInv; 45 | } 46 | 47 | public override string ToString() 48 | { 49 | return $"{yMin} && {xOfMin} && {yMax} && {xOfMax} && {mInv}"; 50 | } 51 | } 52 | 53 | [Serializable] 54 | class Filler 55 | { 56 | List prePoints; 57 | List points = null; 58 | 59 | List vertices = new List(); 60 | List> indicies = new List>(); 61 | List AET = new List(); 62 | 63 | Color? fillColor; 64 | Bitmap fillImage; 65 | 66 | Dictionary imagePoints; 67 | 68 | public Filler(List pVertices, Color? fillColor = null, Bitmap fillImage = null) 69 | { 70 | var dict = new Dictionary(); 71 | 72 | for (int i = 0; i < pVertices.Count; i++) 73 | { 74 | vertices.Add(pVertices[i]); 75 | dict.Add(i, pVertices[i].Y); 76 | } 77 | 78 | indicies = dict.OrderBy(x => x.Value).ToList(); 79 | 80 | this.fillColor = fillColor; 81 | if (fillImage != null) 82 | { 83 | this.fillImage = fillImage; 84 | } 85 | } 86 | 87 | public void UpdatePoints(List points) 88 | { 89 | vertices = new List(points); 90 | this.points = null; 91 | } 92 | 93 | public List FillPoints(Rectangle boundingRect = null) 94 | { 95 | if (this.points != null && boundingRect == null) 96 | return this.points; 97 | 98 | prePoints = new List(); 99 | 100 | int k = 0; 101 | int i = indicies[k].Key; 102 | int y, ymin; 103 | y = ymin = vertices[indicies[0].Key].Y; 104 | int ymax = vertices[indicies[indicies.Count - 1].Key].Y; 105 | 106 | int len = vertices.Count; 107 | 108 | while (y < ymax) 109 | { 110 | while (vertices[i].Y == y) 111 | { 112 | if (vertices[(i - 1 + len) % len].Y > vertices[i].Y) 113 | AET.Add(new ActiveEdgeTableEntry(vertices[i], vertices[(i - 1 + len) % len])); 114 | 115 | if (vertices[(i + 1) % len].Y > vertices[i].Y) 116 | AET.Add(new ActiveEdgeTableEntry(vertices[i], vertices[(i + 1) % len])); 117 | 118 | i = indicies[++k].Key; 119 | } 120 | 121 | AET.Sort(delegate (ActiveEdgeTableEntry e1, ActiveEdgeTableEntry e2) 122 | { 123 | return e1.xOfMin.CompareTo(e2.xOfMin); 124 | }); 125 | 126 | for (int t = 0; t < AET.Count; t += 2) 127 | for (int x1 = (int)AET[t].xOfMin; x1 <= AET[(t + 1) % AET.Count].xOfMin; x1++) 128 | { 129 | if (boundingRect != null && (x1 > boundingRect.GetCorner(1).X || x1 < boundingRect.GetCorner(0).X || y > boundingRect.GetCorner(0).Y || y < boundingRect.GetCorner(2).Y)) 130 | continue; 131 | prePoints.Add(new Point(x1, y)); 132 | } 133 | 134 | ++y; 135 | for (int t = 0; t < AET.Count; t++) 136 | { 137 | AET[t] = new ActiveEdgeTableEntry(AET[t]); 138 | if (AET[t].yMax == y) 139 | AET.RemoveAt(t--); 140 | } 141 | 142 | } 143 | 144 | points = new List(); 145 | 146 | if (fillColor.HasValue) 147 | foreach (var p in prePoints) 148 | points.Add(new ColorPoint(fillColor.Value, p)); 149 | 150 | else 151 | foreach (var kv in fillImage.GetPixels(prePoints, true)) 152 | points.Add(new ColorPoint(kv.Value, kv.Key)); 153 | 154 | return points; 155 | } 156 | 157 | ColorPoint AddPoint(Point point) 158 | { 159 | if (fillColor.HasValue) 160 | return new ColorPoint(fillColor.Value, point); 161 | 162 | return new ColorPoint(fillImage.GetPixelFast(point.X % fillImage.Width, point.Y % fillImage.Height), point); 163 | } 164 | 165 | 166 | } 167 | 168 | public struct FillLog 169 | { 170 | public Color seedCol; 171 | public Point seedPoint; 172 | 173 | public FillLog(Color col, Point p) 174 | { 175 | seedCol = col; 176 | seedPoint = p; 177 | } 178 | } 179 | 180 | public static class FloodFiller 181 | { 182 | public static Bitmap FourWayFloodFill(Bitmap bmp, Color COLOR, Point q) 183 | // https://stackoverflow.com/questions/1257117/a-working-non-recursive-floodfill-algorithm-written-in-c/1257195 184 | { 185 | int h = bmp.Height; 186 | int w = bmp.Width; 187 | 188 | if (q.Y < 0 || q.Y > h - 1 || q.X < 0 || q.X > w - 1) 189 | return bmp; 190 | 191 | Color SEED_COLOR = bmp.GetPixelFast(q.X, q.Y); 192 | 193 | Stack stack = new Stack(); 194 | stack.Push(q); 195 | while (stack.Count > 0) 196 | { 197 | Point p = stack.Pop(); 198 | int x = p.X; 199 | int y = p.Y; 200 | if (y < 0 || y > h - 1 || x < 0 || x > w - 1) 201 | continue; 202 | Color val = bmp.GetPixelFast(x, y); 203 | if (val == SEED_COLOR) 204 | { 205 | bmp.SetPixelFast(x, y, COLOR); 206 | stack.Push(new Point(x + 1, y)); 207 | stack.Push(new Point(x - 1, y)); 208 | stack.Push(new Point(x, y + 1)); 209 | stack.Push(new Point(x, y - 1)); 210 | } 211 | } 212 | return bmp; 213 | } 214 | 215 | } 216 | } -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/MidPointCircle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace winforms_image_processor 9 | { 10 | [Serializable] 11 | class MidPointCircle : Shape 12 | { 13 | Point? center = null; 14 | int? radius = null; 15 | 16 | public MidPointCircle(Color color) : base(color) 17 | { shapeType = DrawingShape.CIRCLE; } 18 | 19 | public MidPointCircle(Color color, Point center, int radius) : base(color) 20 | { 21 | shapeType = DrawingShape.CIRCLE; 22 | this.center = center; 23 | this.radius = radius; 24 | } 25 | 26 | public override string ToString() 27 | { 28 | return "Circle"; 29 | } 30 | 31 | public override int AddPoint(Point point) 32 | { 33 | if (center == null) 34 | center = point; 35 | else if (radius == null) 36 | { 37 | radius = (int)Math.Sqrt(Math.Pow(point.X - center.Value.X, 2) + Math.Pow(point.Y - center.Value.Y, 2)); 38 | return 1; 39 | } 40 | return 0; 41 | } 42 | 43 | public List getSemiCircle(double angle) 44 | { 45 | if (!center.HasValue || !radius.HasValue) 46 | throw new MissingMemberException(); 47 | 48 | if (radius.Value == 0) 49 | return new List() { new ColorPoint(shapeColor, center.Value) }; 50 | 51 | var points = new List(); 52 | 53 | int x = radius.Value, y = 0; 54 | int P = 1 - x; 55 | 56 | while (x > y) 57 | { 58 | 59 | y++; 60 | 61 | if (P <= 0) 62 | P = P + 2 * y + 1; 63 | else 64 | { 65 | x--; 66 | P = P + 2 * y - 2 * x + 1; 67 | } 68 | 69 | if (x < y) 70 | break; 71 | 72 | points.Add(new ColorPoint(shapeColor, new Point(x + center.Value.X, y + center.Value.Y))); 73 | points.Add(new ColorPoint(shapeColor, new Point(x + center.Value.X, -y + center.Value.Y))); 74 | 75 | if (x != y) 76 | { 77 | points.Add(new ColorPoint(shapeColor, new Point(y + center.Value.X, x + center.Value.Y))); 78 | points.Add(new ColorPoint(shapeColor, new Point(y + center.Value.X, -x + center.Value.Y))); 79 | } 80 | } 81 | 82 | var sin = Math.Sin(angle); 83 | var cos = Math.Cos(angle); 84 | 85 | for (int i = 0; i < points.Count; i++) 86 | { 87 | x = (int)Math.Round((points[i].Point.X - center.Value.X) * cos - (points[i].Point.Y - center.Value.Y) * sin + center.Value.X); 88 | y = (int)Math.Round((points[i].Point.X - center.Value.X) * sin + (points[i].Point.Y - center.Value.Y) * cos + center.Value.Y); 89 | 90 | points[i] = new ColorPoint(shapeColor, new Point(x, y)); 91 | } 92 | 93 | return points; 94 | } 95 | 96 | public override List GetPixels(params object[] param) 97 | // https://www.geeksforgeeks.org/mid-point-circle-drawing-algorithm/ 98 | { 99 | if (!center.HasValue || !radius.HasValue) 100 | throw new MissingMemberException(); 101 | 102 | if (radius.Value == 0) 103 | return new List() { new ColorPoint(shapeColor, center.Value) }; 104 | 105 | var points = new List(); 106 | 107 | int x = radius.Value, y = 0; 108 | int P = 1 - x; 109 | 110 | while (x > y) 111 | { 112 | 113 | y++; 114 | 115 | if (P <= 0) 116 | P = P + 2 * y + 1; 117 | else 118 | { 119 | x--; 120 | P = P + 2 * y - 2 * x + 1; 121 | } 122 | 123 | if (x < y) 124 | break; 125 | 126 | points.Add(new ColorPoint(shapeColor, new Point(x + center.Value.X, y + center.Value.Y))); 127 | points.Add(new ColorPoint(shapeColor, new Point(-x + center.Value.X, y + center.Value.Y))); 128 | points.Add(new ColorPoint(shapeColor, new Point(x + center.Value.X, -y + center.Value.Y))); 129 | points.Add(new ColorPoint(shapeColor, new Point(-x + center.Value.X, -y + center.Value.Y))); 130 | 131 | // If the generated point is on the 132 | // line x = y then the perimeter points 133 | // have already been printed 134 | if (x != y) 135 | { 136 | points.Add(new ColorPoint(shapeColor, new Point(y + center.Value.X, x + center.Value.Y))); 137 | points.Add(new ColorPoint(shapeColor, new Point(-y + center.Value.X, x + center.Value.Y))); 138 | points.Add(new ColorPoint(shapeColor, new Point(y + center.Value.X, -x + center.Value.Y))); 139 | points.Add(new ColorPoint(shapeColor, new Point(-y + center.Value.X, -x + center.Value.Y))); 140 | } 141 | } 142 | 143 | return points; 144 | } 145 | 146 | public override void MovePoints(Point displacement) 147 | { 148 | center = center.Value + (Size)displacement; 149 | } 150 | 151 | public override string howToDraw() 152 | { 153 | return "Click center and radius"; 154 | } 155 | 156 | public override List GetPixelsAA(Bitmap bmp) 157 | { 158 | throw new NotImplementedException(); 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/MidPointLine.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace winforms_image_processor 9 | { 10 | [Serializable] 11 | class MidPointLine : Shape 12 | { 13 | public Point? startPoint = null; 14 | public Point? endPoint = null; 15 | public int thickness; 16 | 17 | Clipping clipper = null; 18 | 19 | public MidPointLine(Color color, int thicc) : base(color) 20 | { 21 | thickness = thicc - 1; 22 | shapeType = DrawingShape.LINE; 23 | supportsAA = true; 24 | } 25 | 26 | public MidPointLine(Color color, int thicc, Point start, Point end) : base(color) 27 | { 28 | thickness = thicc - 1; 29 | shapeType = DrawingShape.LINE; 30 | startPoint = start; 31 | endPoint = end; 32 | } 33 | 34 | public MidPointLine(Color color, int thicc, Point start, Point end, Clipping clip) : base(color) 35 | { 36 | thickness = thicc - 1; 37 | shapeType = DrawingShape.LINE; 38 | startPoint = start; 39 | endPoint = end; 40 | clipper = clip; 41 | } 42 | 43 | public override string ToString() 44 | { 45 | return "Line"; 46 | } 47 | 48 | public override int AddPoint(Point point) 49 | { 50 | if (startPoint == null) 51 | startPoint = point; 52 | else if (endPoint == null) 53 | { 54 | endPoint = point; 55 | return 1; 56 | } 57 | return 0; 58 | } 59 | 60 | public override List GetPixels(params object[] param) 61 | { 62 | Line line = new Line(startPoint.Value, endPoint.Value); 63 | 64 | if (clipper != null && !clipper.ClipLine(ref line)) 65 | return new List(); 66 | 67 | return BresenhamMidPointAlgorithm(line.Start, line.End); 68 | } 69 | 70 | public override List GetPixelsAA(Bitmap bmp) 71 | { 72 | Line line = new Line(startPoint.Value, endPoint.Value); 73 | 74 | if (clipper != null && !clipper.ClipLine(ref line)) 75 | return new List(); 76 | 77 | return GuptaSproullAlgorithm(bmp, line.Start, line.End); 78 | } 79 | 80 | List BresenhamMidPointAlgorithm(Point start, Point end) 81 | // https://stackoverflow.com/questions/11678693/all-cases-covered-bresenhams-line-algorithm 82 | { 83 | List points = new List(); 84 | 85 | int x = start.X, y = start.Y; 86 | int x2 = end.X, y2 = end.Y; 87 | 88 | int w = x2 - x; 89 | int h = y2 - y; 90 | int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0; 91 | if (w < 0) dx1 = -1; else if (w > 0) dx1 = 1; 92 | if (h < 0) dy1 = -1; else if (h > 0) dy1 = 1; 93 | if (w < 0) dx2 = -1; else if (w > 0) dx2 = 1; 94 | int longest = Math.Abs(w); 95 | int shortest = Math.Abs(h); 96 | if (!(longest > shortest)) 97 | { 98 | longest = Math.Abs(h); 99 | shortest = Math.Abs(w); 100 | if (h < 0) dy2 = -1; else if (h > 0) dy2 = 1; 101 | dx2 = 0; 102 | } 103 | int numerator = longest >> 1; 104 | for (int i = 0; i <= longest; i++) 105 | { 106 | points.Add(new ColorPoint(shapeColor, new Point(x, y))); 107 | if (Math.Abs(h) > Math.Abs(w)) 108 | for (int j = 1; j < thickness; j++) 109 | { 110 | points.Add(new ColorPoint(shapeColor, new Point(x - j, y))); 111 | points.Add(new ColorPoint(shapeColor, new Point(x + j, y))); 112 | } 113 | else if (Math.Abs(w) > Math.Abs(h)) 114 | for (int j = 1; j < thickness; j++) 115 | { 116 | points.Add(new ColorPoint(shapeColor, new Point(x - j, y))); 117 | points.Add(new ColorPoint(shapeColor, new Point(x + j, y))); 118 | } 119 | 120 | numerator += shortest; 121 | if (!(numerator < longest)) 122 | { 123 | numerator -= longest; 124 | x += dx1; 125 | y += dy1; 126 | } 127 | else 128 | { 129 | x += dx2; 130 | y += dy2; 131 | } 132 | } 133 | 134 | return points; 135 | } 136 | 137 | List GuptaSproullAlgorithm(Bitmap bmp, Point start, Point end) 138 | // http://elynxsdk.free.fr/ext-docs/Rasterization/Antialiasing/Gupta%20sproull%20antialiased%20lines.htm 139 | // https://jamesarich.weebly.com/uploads/1/4/0/3/14035069/480xprojectreport.pdf 140 | { 141 | var points = new List(); 142 | 143 | int x1 = start.X, y1 = start.Y; 144 | int x2 = end.X, y2 = end.Y; 145 | 146 | int dx = x2 - x1; 147 | int dy = y2 - y1; 148 | 149 | int du, dv, u, x, y, ix, iy; 150 | 151 | // By switching to (u,v), we combine all eight octant 152 | int adx = dx < 0 ? -dx : dx; 153 | int ady = dy < 0 ? -dy : dy; 154 | x = x1; 155 | y = y1; 156 | if (adx > ady) 157 | { 158 | du = adx; 159 | dv = ady; 160 | u = x2; 161 | ix = dx < 0 ? -1 : 1; 162 | iy = dy < 0 ? -1 : 1; 163 | } 164 | else 165 | { 166 | du = ady; 167 | dv = adx; 168 | u = y2; 169 | ix = dx < 0 ? -1 : 1; 170 | iy = dy < 0 ? -1 : 1; 171 | } 172 | 173 | int uEnd = u + du; 174 | int d = (2 * dv) - du; // Initial value as in Bresenham's 175 | int incrS = 2 * dv; // Δd for straight increments 176 | int incrD = 2 * (dv - du); // Δd for diagonal increments 177 | int twovdu = 0; // Numerator of distance 178 | double invD = 1.0 / (2.0 * Math.Sqrt(du * du + dv * dv)); // Precomputed inverse denominator 179 | double invD2du = 2.0 * (du * invD); // Precomputed constant 180 | 181 | if (adx > ady) 182 | { 183 | do 184 | { 185 | points.Add(newColorPixel(bmp, x, y, twovdu * invD)); 186 | points.Add(newColorPixel(bmp, x, y + iy, invD2du - twovdu * invD)); 187 | points.Add(newColorPixel(bmp, x, y - iy, invD2du + twovdu * invD)); 188 | 189 | 190 | if (d < 0) 191 | { 192 | // Choose straight 193 | twovdu = d + du; 194 | d += incrS; 195 | 196 | } 197 | else 198 | { 199 | // Choose diagonal 200 | twovdu = d - du; 201 | d += incrD; 202 | y += iy; 203 | } 204 | u++; 205 | x += ix; 206 | } while (u < uEnd); 207 | } 208 | else 209 | { 210 | do 211 | { 212 | points.Add(newColorPixel(bmp, x, y, twovdu * invD)); 213 | points.Add(newColorPixel(bmp, x, y + iy, invD2du - twovdu * invD)); 214 | points.Add(newColorPixel(bmp, x, y - iy, invD2du + twovdu * invD)); 215 | 216 | if (d < 0) 217 | { 218 | // Choose straight 219 | twovdu = d + du; 220 | d += incrS; 221 | } 222 | else 223 | { 224 | // Choose diagonal 225 | twovdu = d - du; 226 | d += incrD; 227 | x += ix; 228 | } 229 | u++; 230 | y += iy; 231 | } while (u < uEnd); 232 | } 233 | 234 | return points; 235 | } 236 | 237 | ColorPoint newColorPixel(Bitmap bmp, int x, int y, double dist) 238 | { 239 | double value = 1 - Math.Pow((dist * 2 / 3), 2); 240 | 241 | Color old = bmp.GetPixelFast(x, y); 242 | Color col = ColorInterpolator.InterpolateBetween(old, shapeColor, value); 243 | 244 | return new ColorPoint(col, new Point(x, y)); 245 | } 246 | 247 | public override void MovePoints(Point displacement) 248 | { 249 | startPoint = startPoint.Value + (Size)displacement; 250 | endPoint = endPoint.Value + (Size)displacement; 251 | } 252 | 253 | public override string howToDraw() 254 | { 255 | return "Click start and end points"; 256 | } 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/Polygon.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace winforms_image_processor 9 | { 10 | [Serializable] 11 | class Polygon : Shape 12 | { 13 | public List points = null; 14 | public int thickness; 15 | 16 | protected Filler filler = null; 17 | 18 | public Polygon(Color color, int thicc) : base(color) 19 | { 20 | thickness = thicc - 1; 21 | shapeType = DrawingShape.POLY; 22 | supportsAA = true; 23 | } 24 | 25 | public override int AddPoint(Point point) 26 | { 27 | if (points == null) 28 | points = new List { point }; 29 | else 30 | { 31 | double dist = (point.X - points[0].X) * (point.X - points[0].X) + (point.Y - points[0].Y) * (point.Y - points[0].Y); 32 | if (dist < 100) 33 | { 34 | points.Add(points[0]); 35 | 36 | return 1; 37 | } 38 | else 39 | points.Add(point); 40 | } 41 | return 0; 42 | } 43 | 44 | public int AddPoint(Point point, out MidPointLine tmpLine) 45 | { 46 | tmpLine = null; 47 | if (points == null) 48 | return AddPoint(point); 49 | 50 | int returnValue = AddPoint(point); 51 | tmpLine = new MidPointLine(shapeColor, thickness, points[points.Count - 2], points.Last()); 52 | return returnValue; 53 | } 54 | 55 | public void SetFiller(Color color) 56 | { 57 | filler = new Filler(points, fillColor: color); 58 | } 59 | 60 | public void SetFiller(string filename) 61 | { 62 | filler = new Filler(points, fillImage: new Bitmap(filename)); 63 | } 64 | 65 | public void UnSetFiller() 66 | { 67 | filler = null; 68 | } 69 | 70 | public override List GetPixels(params object[] param) 71 | { 72 | var pixels = new List(); 73 | 74 | if (filler != null) 75 | pixels.AddRange(filler.FillPoints()); 76 | 77 | for (int i = 0; i <= points.Count - 2; i++) 78 | pixels.AddRange(new MidPointLine(shapeColor, thickness, points[i], points[i + 1]).GetPixels()); 79 | 80 | return pixels; 81 | } 82 | 83 | public override string howToDraw() 84 | { 85 | return "Click each point and click on first to finish."; 86 | } 87 | 88 | public override void MovePoints(Point displacement) 89 | { 90 | for (int i = 0; i < points.Count; i++) 91 | points[i] = points[i] + (Size)displacement; 92 | 93 | if (filler != null) 94 | filler.UpdatePoints(points); 95 | } 96 | 97 | public override List GetPixelsAA(Bitmap bmp) 98 | { 99 | var pixels = new List(); 100 | 101 | if (filler != null) 102 | pixels.AddRange(filler.FillPoints()); 103 | 104 | for (int i = 0; i <= points.Count - 2; i++) 105 | pixels.AddRange((new MidPointLine(shapeColor, thickness, points[i], points[i + 1])).GetPixelsAA(bmp)); 106 | 107 | return pixels; 108 | } 109 | 110 | public override string ToString() 111 | { 112 | return "Polygon"; 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/Rectangle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace winforms_image_processor 9 | { 10 | [Serializable] 11 | class Rectangle : Shape 12 | { 13 | public Point? startPoint = null; 14 | public Point? endPoint = null; 15 | int thickness; 16 | 17 | List orderedPoints = new List(); 18 | 19 | public Rectangle(Color color, int thicc) : base(color) 20 | { 21 | shapeType = DrawingShape.RECT; 22 | thickness = thicc; 23 | supportsAA = true; 24 | } 25 | 26 | public override int AddPoint(Point point) 27 | { 28 | if (startPoint == null) 29 | startPoint = point; 30 | 31 | else if (endPoint == null) 32 | { 33 | endPoint = point; 34 | return 1; 35 | } 36 | 37 | return 0; 38 | } 39 | 40 | void OrderPoints() 41 | // 0 highest y and lowest x 42 | { 43 | Point revStartPoint = new Point(startPoint.Value.X, endPoint.Value.Y); 44 | Point revEndPoint = new Point(endPoint.Value.X, startPoint.Value.Y); 45 | 46 | if (startPoint.Value.X > endPoint.Value.X) 47 | { 48 | if (startPoint.Value.Y > endPoint.Value.Y) 49 | { 50 | orderedPoints.Add(revEndPoint); 51 | orderedPoints.Add(startPoint.Value); 52 | orderedPoints.Add(revStartPoint); 53 | orderedPoints.Add(endPoint.Value); 54 | 55 | return; 56 | } 57 | 58 | orderedPoints.Add(endPoint.Value); 59 | orderedPoints.Add(revStartPoint); 60 | orderedPoints.Add(startPoint.Value); 61 | orderedPoints.Add(revEndPoint); 62 | 63 | return; 64 | } 65 | 66 | if (startPoint.Value.Y > endPoint.Value.Y) 67 | { 68 | orderedPoints.Add(startPoint.Value); 69 | orderedPoints.Add(revEndPoint); 70 | orderedPoints.Add(endPoint.Value); 71 | orderedPoints.Add(revStartPoint); 72 | 73 | return; 74 | } 75 | 76 | orderedPoints.Add(revStartPoint); 77 | orderedPoints.Add(endPoint.Value); 78 | orderedPoints.Add(revEndPoint); 79 | orderedPoints.Add(startPoint.Value); 80 | 81 | return; 82 | } 83 | 84 | public Point GetCorner(int corner) 85 | { 86 | OrderPoints(); 87 | 88 | return orderedPoints[corner]; 89 | } 90 | 91 | public override List GetPixels(params object[] param) 92 | { 93 | var points = new List(); 94 | 95 | Point upperLeft = new Point(startPoint.Value.X, endPoint.Value.Y); 96 | Point lowerRight = new Point(endPoint.Value.X, startPoint.Value.Y); 97 | 98 | points.AddRange(new MidPointLine(shapeColor, thickness, startPoint.Value, upperLeft).GetPixels()); 99 | points.AddRange(new MidPointLine(shapeColor, thickness, upperLeft, endPoint.Value).GetPixels()); 100 | points.AddRange(new MidPointLine(shapeColor, thickness, endPoint.Value, lowerRight).GetPixels()); 101 | points.AddRange(new MidPointLine(shapeColor, thickness, lowerRight, startPoint.Value).GetPixels()); 102 | 103 | return points; 104 | } 105 | 106 | public override List GetPixelsAA(Bitmap bmp) 107 | { 108 | var points = new List(); 109 | 110 | Point upperLeft = new Point(startPoint.Value.X, endPoint.Value.Y); 111 | Point lowerRight = new Point(endPoint.Value.X, startPoint.Value.Y); 112 | 113 | points.AddRange(new MidPointLine(shapeColor, thickness, startPoint.Value, upperLeft).GetPixelsAA(bmp)); 114 | points.AddRange(new MidPointLine(shapeColor, thickness, upperLeft, endPoint.Value).GetPixelsAA(bmp)); 115 | points.AddRange(new MidPointLine(shapeColor, thickness, endPoint.Value, lowerRight).GetPixelsAA(bmp)); 116 | points.AddRange(new MidPointLine(shapeColor, thickness, lowerRight, startPoint.Value).GetPixelsAA(bmp)); 117 | 118 | return points; 119 | } 120 | 121 | public override void MovePoints(Point displacement) 122 | { 123 | startPoint = startPoint.Value + (Size)displacement; 124 | endPoint = endPoint.Value + (Size)displacement; 125 | } 126 | 127 | public override string ToString() 128 | { 129 | return "Rectangle"; 130 | } 131 | 132 | public override string howToDraw() 133 | { 134 | return "Click point lower left and point upper right."; 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /winforms-image-processor/DrawTools/Shape.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace winforms_image_processor 9 | { 10 | [Serializable] 11 | public struct ColorPoint 12 | { 13 | public Color Color; 14 | public Point Point; 15 | 16 | public ColorPoint(Color col, Point p) 17 | { 18 | Color = col; 19 | Point = p; 20 | } 21 | } 22 | 23 | [Serializable] 24 | abstract class Shape 25 | { 26 | public DrawingShape shapeType; 27 | public Color shapeColor; 28 | public bool supportsAA = false; 29 | 30 | public Shape(Color color) 31 | { shapeColor = color; } 32 | 33 | public abstract override string ToString(); 34 | 35 | abstract public int AddPoint(Point point); 36 | 37 | abstract public List GetPixelsAA(Bitmap bmp); 38 | 39 | abstract public List GetPixels(params object[] param); 40 | // Params: 41 | // [0] : bool for clip border draw 42 | 43 | abstract public void MovePoints(Point displacement); 44 | 45 | abstract public string howToDraw(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /winforms-image-processor/Filters/BitmapExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Drawing.Imaging; 5 | using System.Linq; 6 | using System.Runtime.InteropServices; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace winforms_image_processor 11 | { 12 | public static class BitmapExtension 13 | { 14 | public static void SetPixelFast(this Bitmap bmp, int x, int y, Color color) 15 | { 16 | var newValues = new byte[] { color.B, color.G, color.R, 255 }; 17 | 18 | BitmapData data = bmp.LockBits( 19 | new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), 20 | ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb 21 | ); 22 | 23 | if ( 24 | data.Stride * y + 4 * x < data.Stride * data.Height 25 | && data.Stride * y + 4 * x >= 0 26 | && x * 4 < data.Stride 27 | && y < data.Height 28 | ) 29 | unsafe 30 | { 31 | byte* ptr = (byte*)data.Scan0; 32 | 33 | for (int i = 0; i < 4; i++) 34 | ptr[data.Stride * y + 4 * x + i] = newValues[i]; 35 | } 36 | 37 | bmp.UnlockBits(data); 38 | } 39 | 40 | public static Color GetPixelFast(this Bitmap bmp, int x, int y) 41 | { 42 | BitmapData data = bmp.LockBits( 43 | new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), 44 | ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb 45 | ); 46 | 47 | Color col = Color.FromArgb(0, 0, 0, 0); ; 48 | 49 | if (data.Stride * y + 4 * x < data.Stride * data.Height && data.Stride * y + 4 * x >= 0) 50 | unsafe 51 | { 52 | byte* ptr = (byte*)data.Scan0; 53 | 54 | col = Color.FromArgb( 55 | ptr[data.Stride * y + 4 * x + 3], 56 | ptr[data.Stride * y + 4 * x + 2], 57 | ptr[data.Stride * y + 4 * x + 1], 58 | ptr[data.Stride * y + 4 * x + 0] 59 | ); 60 | } 61 | 62 | bmp.UnlockBits(data); 63 | 64 | return col; 65 | } 66 | 67 | public static Dictionary GetPixels(this Bitmap bmp, List list, bool wrapping) 68 | { 69 | var dict = new Dictionary(); 70 | 71 | BitmapData data = bmp.LockBits( 72 | new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), 73 | ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb 74 | ); 75 | 76 | Color col = Color.FromArgb(0, 0, 0, 0); ; 77 | 78 | foreach (var l in list) 79 | { 80 | int y = l.Y; 81 | int x = l.X; 82 | if (wrapping) 83 | { 84 | y = y % bmp.Height; 85 | x = x % bmp.Width; 86 | } 87 | 88 | if (data.Stride * y + 4 * x < data.Stride * data.Height && data.Stride * y + 4 * x >= 0) 89 | unsafe 90 | { 91 | byte* ptr = (byte*)data.Scan0; 92 | 93 | dict.Add(l, Color.FromArgb( 94 | ptr[data.Stride * y + 4 * x + 3], 95 | ptr[data.Stride * y + 4 * x + 2], 96 | ptr[data.Stride * y + 4 * x + 1], 97 | ptr[data.Stride * y + 4 * x + 0] 98 | )); 99 | } 100 | } 101 | 102 | bmp.UnlockBits(data); 103 | 104 | return dict; 105 | } 106 | 107 | public static Dictionary GetColorsAsDict(this Bitmap bmp) 108 | { 109 | var dict = new Dictionary(); 110 | 111 | int width = bmp.Width; 112 | int height = bmp.Height; 113 | BitmapData srcData = bmp.LockBits( 114 | new System.Drawing.Rectangle(0, 0, width, height), 115 | ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb 116 | ); 117 | 118 | int stride = srcData.Stride; 119 | int bytes = srcData.Stride * srcData.Height; 120 | byte[] buffer = new byte[bytes]; 121 | Marshal.Copy(srcData.Scan0, buffer, 0, bytes); 122 | 123 | bmp.UnlockBits(srcData); 124 | 125 | int i = 0; 126 | for (int x = 0; x < width; x++) 127 | for (int y = 0; y < height; y++) 128 | { 129 | i = stride * y + 4 * x; 130 | dict.Add(new Point(x, y), Color.FromArgb(buffer[i + 3], buffer[i + 2], buffer[i + 1], buffer[i])); 131 | } 132 | 133 | return dict; 134 | } 135 | 136 | public static byte[] GetBitmapDataBytes(this Bitmap bmp, out int stride) 137 | { 138 | int width = bmp.Width; 139 | int height = bmp.Height; 140 | BitmapData srcData = bmp.LockBits( 141 | new System.Drawing.Rectangle(0, 0, width, height), 142 | ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb 143 | ); 144 | 145 | stride = srcData.Stride; 146 | int bytes = srcData.Stride * srcData.Height; 147 | byte[] buffer = new byte[bytes]; 148 | Marshal.Copy(srcData.Scan0, buffer, 0, bytes); 149 | 150 | bmp.UnlockBits(srcData); 151 | 152 | return buffer; 153 | } 154 | 155 | public static byte[] GetBitmapDataBytes(this Bitmap bmp) 156 | { 157 | int width = bmp.Width; 158 | int height = bmp.Height; 159 | BitmapData srcData = bmp.LockBits( 160 | new System.Drawing.Rectangle(0, 0, width, height), 161 | ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb 162 | ); 163 | 164 | int bytes = srcData.Stride * srcData.Height; 165 | byte[] buffer = new byte[bytes]; 166 | Marshal.Copy(srcData.Scan0, buffer, 0, bytes); 167 | 168 | bmp.UnlockBits(srcData); 169 | 170 | return buffer; 171 | } 172 | 173 | public static void SetBitmapDataBytes(this Bitmap bmp, byte[] bytes) 174 | { 175 | BitmapData resData = bmp.LockBits( 176 | new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), 177 | ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb 178 | ); 179 | 180 | Marshal.Copy(bytes, 0, resData.Scan0, bytes.Length); 181 | 182 | bmp.UnlockBits(resData); 183 | } 184 | 185 | static public Bitmap ApplyFilter(this Bitmap bmp, Func filter) 186 | { 187 | byte[] buffer = bmp.GetBitmapDataBytes(); 188 | byte[] result = filter(buffer); 189 | 190 | Bitmap bmpRes = new Bitmap(bmp.Width, bmp.Height); 191 | bmpRes.SetBitmapDataBytes(result); 192 | 193 | return bmpRes; 194 | } 195 | 196 | static public Bitmap ApplyFilter(this Bitmap bmp, Func filter, CustomKernel customKernel) 197 | { 198 | byte[] buffer = bmp.GetBitmapDataBytes(out int stride); 199 | byte[] result = filter(buffer, stride, customKernel); 200 | 201 | Bitmap bmpRes = new Bitmap(bmp.Width, bmp.Height); 202 | bmpRes.SetBitmapDataBytes(result); 203 | 204 | return bmpRes; 205 | } 206 | } 207 | } -------------------------------------------------------------------------------- /winforms-image-processor/Filters/ColorspaceTools.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace winforms_image_processor 8 | { 9 | static class ColorspaceTools 10 | { 11 | public static void RGBtoYBR(int R, int G, int B, out int Y, out int Cb, out int Cr) 12 | { 13 | Y = (int)((0.299 * R) + (0.587 * G) + (0.114 * B)); 14 | Cb = (int)(128 - (0.168736 * R) + (0.331264 * G) + (0.5 * B)); 15 | Cr = (int)(128 + (0.5 * R) + (0.418688 * G) + (0.081312 * B)); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /winforms-image-processor/Filters/Constants.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace winforms_image_processor 8 | { 9 | static class Constants 10 | { 11 | public static double filterGammaValue = 1.5; 12 | 13 | public static double filterBrightnessValue = 10; 14 | 15 | public static double filterContrastValue = 10; 16 | 17 | public static int filterOctreeColorLimit = 16; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /winforms-image-processor/Filters/FilterManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Drawing; 5 | using System.Drawing.Imaging; 6 | using System.Linq; 7 | using System.Runtime.InteropServices; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace winforms_image_processor 12 | { 13 | /// 14 | /// The FilterManager Class is responsible for applying filters to the given image. 15 | /// 16 | static class FilterManager 17 | // Expression lambdas: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions 18 | { 19 | public static Dictionary> filterMapping = new Dictionary> { 20 | { "Inversion", (bmp) => bmp.ApplyFilter(Inversion) }, 21 | { "Gamma", (bmp) => bmp.ApplyFilter(Gamma)}, 22 | { "Brightness Correction", (bmp) => bmp.ApplyFilter(Brightness) }, 23 | { "Contrast Correction", (bmp) => bmp.ApplyFilter(Contrast) }, 24 | 25 | { "Grayscale", (bmp) => bmp.ApplyFilter(Grayscale) }, 26 | { "Average Dither", (bmp) => bmp.ApplyFilter(AverageDither) }, 27 | { "Octree Quantization", (bmp) => bmp.ApplyFilter(OctreeQuantization) }, 28 | 29 | { "Sharpen", (bmp) => bmp.ApplyFilter(ApplyKernel, Kernel.SharpenKernel) }, 30 | { "Gaussian Blur", (bmp) => bmp.ApplyFilter(ApplyKernel, Kernel.GaussianBlurKernel) }, 31 | { "Box Blur", (bmp) => bmp.ApplyFilter(ApplyKernel, Kernel.BoxBlurKernel) }, 32 | { "Emboss", (bmp) => bmp.ApplyFilter(ApplyKernel, Kernel.EmbossKernel) }, 33 | { "Outline", (bmp) => bmp.ApplyFilter(ApplyKernel, Kernel.OutlineKernel) }, 34 | }; 35 | 36 | public static void UpdateFilterMapping(string filter) 37 | { 38 | filterMapping.Add( 39 | filter, 40 | (bmp) => bmp.ApplyFilter(ApplyKernel, Kernel.customKernels[filter]) 41 | ); 42 | } 43 | 44 | public static Bitmap RecreateFilterStateFromState(Bitmap originalImage, List state) 45 | { 46 | Debug.Print("Recreating filter state"); 47 | 48 | foreach (string filter in state) 49 | originalImage = filterMapping[filter](originalImage); 50 | 51 | return originalImage; 52 | } 53 | 54 | /////////////////////// 55 | // Function Filters // 56 | ///////////////////// 57 | 58 | static public byte[] Inversion(byte[] buffer) 59 | // Inversion filter https://stackoverflow.com/questions/33024881/invert-image-faster-in-c-sharp 60 | { 61 | byte[] result = new byte[buffer.Length]; 62 | int inv = 0; 63 | for (int i = 0; i < buffer.Length; i++) 64 | { 65 | if ((i + 1) % 4 == 0) 66 | { 67 | result[i] = buffer[i]; 68 | continue; 69 | } 70 | 71 | inv = 255 - buffer[i]; 72 | result[i] = (byte)inv; 73 | } 74 | return result; 75 | } 76 | 77 | static public byte[] Gamma(byte[] buffer) 78 | // Gamma filter https://epochabuse.com/csharp-gamma-correction/ 79 | { 80 | var gamma = Constants.filterGammaValue; 81 | 82 | byte[] result = new byte[buffer.Length]; 83 | 84 | for (int i = 0; i < buffer.Length; i++) 85 | { 86 | if ((i + 1) % 4 == 0) 87 | { 88 | result[i] = buffer[i]; 89 | continue; 90 | } 91 | 92 | double range = (double)buffer[i] / 255; 93 | double correction = 1d * Math.Pow(range, gamma); 94 | result[i] = (byte)(correction * 255); 95 | 96 | } 97 | return result; 98 | } 99 | 100 | static public byte[] Brightness(byte[] buffer) 101 | //Brightness correct https://www.developerfusion.com/article/5441/image-manipulation-brightness-and-contrast/2/ 102 | //Brightness algorithm https://www.dfstudios.co.uk/articles/programming/image-programming-algorithms/image-processing-algorithms-part-4-brightness-adjustment/ 103 | { 104 | var brightness = Constants.filterBrightnessValue; 105 | 106 | byte[] result = new byte[buffer.Length]; 107 | 108 | for (int i = 0; i < buffer.Length; i++) 109 | { 110 | if ((i + 1) % 4 == 0) 111 | { 112 | result[i] = buffer[i]; 113 | continue; 114 | } 115 | result[i] = (byte)(brightness > 0 ? Math.Min(buffer[i] + brightness, 255) : Math.Max(buffer[i] + brightness, 0)); 116 | 117 | } 118 | 119 | return result; 120 | } 121 | 122 | static public byte[] Contrast(byte[] buffer) 123 | //Contrast algorithm https://www.dfstudios.co.uk/articles/programming/image-programming-algorithms/image-processing-algorithms-part-5-contrast-adjustment/ 124 | { 125 | var corrFactor = Math.Pow((100.0 + Constants.filterContrastValue) / 100.0, 2); 126 | 127 | byte[] result = new byte[buffer.Length]; 128 | 129 | int cnt = 0, value; 130 | for (int i = 0; i < buffer.Length; i++) 131 | { 132 | if ((i + 1) % 4 == 0) 133 | { 134 | result[i] = buffer[i]; 135 | continue; 136 | } 137 | 138 | value = (int)(((((buffer[i] / 255.0) - 0.5) * corrFactor) + 0.5) * 255.0); 139 | cnt = (value < 0) ? 0 : (value > 255) ? 255 : value; 140 | result[i] = (byte)cnt; 141 | } 142 | return result; 143 | } 144 | 145 | ///////////////////////// 146 | // Convultion Filters // 147 | /////////////////////// 148 | 149 | static public byte[] ApplyKernel(byte[] buffer, int stride, CustomKernel customKernel) 150 | { 151 | double[,] kernel = customKernel.GetKernel(); 152 | byte[] result = new byte[buffer.Length]; 153 | 154 | // 1D Bitmap byte data 155 | for (int i = 0; i < buffer.Length; i++) 156 | { 157 | if ((i + 1) % 4 == 0) 158 | { 159 | result[i] = buffer[i]; 160 | continue; 161 | } 162 | 163 | double newByte = 0; 164 | bool ignorePixel = false; 165 | 166 | // Kernel Columns 167 | int lowerColBound = -kernel.GetLength(0) / 2 - customKernel.anchor.X; 168 | int upperColBound = kernel.GetLength(0) / 2 - customKernel.anchor.X; 169 | for (int j = lowerColBound; j <= upperColBound; j++) 170 | { 171 | if ((i + 4 * j < 0) || (i + 4 * j >= buffer.Length) || ignorePixel) 172 | { 173 | newByte = 0; 174 | break; 175 | } 176 | 177 | // Kernel Rows 178 | int lowerRowBound = -kernel.GetLength(1) / 2 - customKernel.anchor.Y; 179 | int upperRowBound = kernel.GetLength(1) / 2 - customKernel.anchor.Y; 180 | for (int k = lowerRowBound; k <= upperRowBound; k++) 181 | { 182 | if ((i + 4 * j + k * stride < 0) || (i + 4 * j + k * stride >= buffer.Length)) 183 | { 184 | ignorePixel = true; 185 | break; 186 | } 187 | 188 | newByte += kernel[ 189 | j - lowerColBound, 190 | k - lowerRowBound] 191 | * buffer[i + 4 * j + k * stride] 192 | + customKernel.offset; 193 | } 194 | } 195 | 196 | result[i] = (byte)(newByte < 0 ? 0 : newByte > 255 ? 255 : newByte); 197 | } 198 | 199 | return result; 200 | } 201 | 202 | //////////////// 203 | // Grayscale // 204 | ////////////// 205 | 206 | static public byte[] Grayscale(byte[] buffer) 207 | // Little Endian byte order https://stackoverflow.com/questions/8104461/pixelformat-format32bppargb-seems-to-have-wrong-byte-order 208 | { 209 | byte[] result = new byte[buffer.Length]; 210 | 211 | for (int i = 0; i < buffer.Length; i = i + 4) 212 | { 213 | result[i + 3] = buffer[i + 3]; 214 | 215 | double grayscale = (buffer[i + 3] * 0.3) + (buffer[i + 2] * 0.59) + (buffer[i] * 0.11); 216 | result[i] = result[i + 1] = result[i + 2] = (byte)grayscale; 217 | } 218 | 219 | return result; 220 | } 221 | 222 | //////////////////////////////////// 223 | // Dither & Quantization Filters // 224 | ////////////////////////////////// 225 | 226 | static public byte[] AverageDither(byte[] buffer) 227 | { 228 | byte[] result = new byte[buffer.Length]; 229 | Point[] sums = new Point[4] { Point.Empty, Point.Empty, Point.Empty, Point.Empty }; 230 | 231 | for (int i = 0; i < buffer.Length; i++) 232 | { 233 | sums[i % 4].X += buffer[i]; 234 | sums[i % 4].Y++; 235 | } 236 | 237 | var thresh = new int[4]; 238 | for (int i = 0; i < 4; i++) 239 | thresh[i] = sums[i].X / sums[i].Y; 240 | 241 | thresh[3] = 255; 242 | 243 | for (int i = 0; i < buffer.Length; i++) 244 | result[i] = (byte)(thresh[i % 4] >= buffer[i] ? 255 : 0); 245 | 246 | return result; 247 | } 248 | 249 | static public byte[] OctreeQuantization(byte[] buffer) 250 | { 251 | byte[] result = new byte[buffer.Length]; 252 | 253 | OctreeQuantizer octree = new OctreeQuantizer(); 254 | 255 | for (int i = 0; i < buffer.Length; i += 4) 256 | octree.AddColor(Color.FromArgb(buffer[i + 2], buffer[i + 1], buffer[i])); 257 | 258 | var limitedPalette = octree.GetPalette(Constants.filterOctreeColorLimit); 259 | 260 | for (int i = 0; i < buffer.Length; i += 4) 261 | { 262 | Color currentPixel = Color.FromArgb(buffer[i + 2], buffer[i + 1], buffer[i]); 263 | Color resultPixel = limitedPalette[octree.GetPaletteIndex(currentPixel)]; 264 | 265 | result[i + 0] = resultPixel.B; 266 | result[i + 1] = resultPixel.G; 267 | result[i + 2] = resultPixel.R; 268 | result[i + 3] = 255; 269 | } 270 | 271 | return result; 272 | } 273 | 274 | /////////////////////////////// 275 | // YCbCr Colorspace Filters // 276 | ///////////////////////////// 277 | 278 | static public byte[] YGrayscale(byte[] buffer) 279 | { 280 | byte[] result = new byte[buffer.Length]; 281 | 282 | for (int i = 0; i < buffer.Length; i += 4) 283 | { 284 | ColorspaceTools.RGBtoYBR(buffer[i + 2], buffer[i + 1], buffer[i], out int Y, out _, out _); 285 | 286 | result[i + 0] = result[i + 1] = result[i + 2] = (byte)Y; 287 | result[i + 3] = 255; 288 | } 289 | 290 | return result; 291 | } 292 | 293 | static public byte[] CbInterpolate(byte[] buffer) 294 | { 295 | byte[] result = new byte[buffer.Length]; 296 | 297 | for (int i = 0; i < buffer.Length; i += 4) 298 | { 299 | ColorspaceTools.RGBtoYBR(buffer[i + 2], buffer[i + 1], buffer[i], out int Y, out int Cb, out int Cr); 300 | 301 | result[i] = (byte)((1 - Cb) * 0 + Cb * 255); 302 | result[i + 1] = (byte) ((1 - Cb) * 255 + Cb * 0); 303 | result[i + 2] = (byte) ((1 - Cb) * 127 + Cb * 127); 304 | result[i + 3] = 255; 305 | } 306 | 307 | return result; 308 | } 309 | 310 | static public byte[] CrInterpolate(byte[] buffer) 311 | { 312 | byte[] result = new byte[buffer.Length]; 313 | 314 | for (int i = 0; i < buffer.Length; i += 4) 315 | { 316 | ColorspaceTools.RGBtoYBR(buffer[i + 2], buffer[i + 1], buffer[i], out int Y, out int Cb, out int Cr); 317 | 318 | result[i] = (byte)((1 - Cr) * 127 + Cr * 127); 319 | result[i + 1] = (byte)((1 - Cr) * 255 + Cr * 0); 320 | result[i + 2] = (byte)((1 - Cr) * 0 + Cr * 255); 321 | result[i + 3] = 255; 322 | } 323 | 324 | return result; 325 | } 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /winforms-image-processor/Filters/Kernel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Diagnostics; 3 | using System.Drawing; 4 | using System.Text; 5 | 6 | namespace winforms_image_processor 7 | { 8 | public struct CustomKernel 9 | { 10 | public double[,] kernel; 11 | public int divisor; 12 | 13 | public int offset; 14 | public Point anchor; 15 | 16 | public CustomKernel(double[,] kernel, int div, int off, Point anch) 17 | { 18 | this.kernel = kernel; 19 | divisor = div; 20 | offset = off; 21 | anchor = anch; 22 | } 23 | 24 | public double[,] GetKernel() 25 | { 26 | double[,] kernelCopy = new double[kernel.GetLength(0), kernel.GetLength(1)]; 27 | for (int i = 0; i < kernel.GetLength(0); i++) 28 | for (int j = 0; j < kernel.GetLength(1); j++) 29 | kernelCopy[i, j] = kernel[i, j] / divisor; 30 | return kernelCopy; 31 | } 32 | 33 | public override string ToString() 34 | { 35 | StringBuilder sb = new StringBuilder("Kernel with following values:\n"); 36 | foreach (int i in kernel) 37 | { 38 | sb.Append(i); 39 | sb.Append(", "); 40 | } 41 | sb.Append("\n"); 42 | sb.Append(divisor); 43 | sb.Append("\n"); 44 | sb.Append(offset); 45 | sb.Append("\n"); 46 | sb.Append(anchor.ToString()); 47 | return sb.ToString(); 48 | } 49 | } 50 | 51 | public static class Kernel 52 | { 53 | public static Dictionary customKernels = new Dictionary(); 54 | 55 | public static CustomKernel SharpenKernel = new CustomKernel(new double[3, 3] { { 0, -1, 0 }, { -1, 5, -1 }, { 0, -1, 0 } }, 1, 0, Point.Empty); 56 | public static CustomKernel OutlineKernel = new CustomKernel(new double[3, 3] { { -1, -1, -1 }, { -1, 8, -1 }, { -1, -1, -1 } }, 1, 0, Point.Empty); 57 | public static CustomKernel EmbossKernel = new CustomKernel(new double[3, 3] { { -2, -1, 0 }, { -1, 1, 1 }, { 0, 1, 2 } }, 1, 0, Point.Empty); 58 | public static CustomKernel BoxBlurKernel = new CustomKernel(new double[3, 3] { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }, 9, 0, Point.Empty); 59 | public static CustomKernel GaussianBlurKernel = new CustomKernel(new double[3, 3] { { 1, 2, 1 }, { 2, 4, 2 }, { 1, 2, 1 } }, 16, 0, Point.Empty); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /winforms-image-processor/Filters/OctreeTools.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Drawing; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace winforms_image_processor 10 | { 11 | // Source for below classes 12 | // https://github.com/pmichna/NewOctree 13 | 14 | internal class OctreeNode 15 | { 16 | private static readonly Byte[] Mask = new Byte[] { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; 17 | 18 | private int red; 19 | private int green; 20 | private int blue; 21 | 22 | private int pixelCount; 23 | private int paletteIndex; 24 | 25 | private readonly OctreeNode[] nodes; 26 | 27 | public OctreeNode(int level, OctreeQuantizer parent) //level - level of parent 28 | { 29 | nodes = new OctreeNode[8]; 30 | 31 | if (level < 7) 32 | { 33 | parent.AddLevelNode(level, this); 34 | } 35 | } 36 | 37 | public Boolean IsLeaf 38 | { 39 | get { return pixelCount > 0; } 40 | } 41 | 42 | public Color Color 43 | { 44 | get 45 | { 46 | Color result; 47 | 48 | // determines a color of the leaf 49 | if (IsLeaf) 50 | { 51 | result = pixelCount == 1 ? 52 | Color.FromArgb(255, red, green, blue) : 53 | Color.FromArgb(255, red / pixelCount, green / pixelCount, blue / pixelCount); 54 | } 55 | else 56 | { 57 | throw new InvalidOperationException("Cannot retrieve a color for other node than leaf."); 58 | } 59 | 60 | return result; 61 | } 62 | } 63 | 64 | public int ActiveNodesPixelCount 65 | { 66 | get 67 | { 68 | int result = pixelCount; 69 | 70 | // sums up all the pixel presence for all the active nodes 71 | for (int index = 0; index < 8; index++) 72 | { 73 | OctreeNode node = nodes[index]; 74 | 75 | if (node != null) 76 | { 77 | result += node.pixelCount; 78 | } 79 | } 80 | 81 | return result; 82 | } 83 | } 84 | 85 | public IEnumerable ActiveNodes 86 | { 87 | get 88 | { 89 | List result = new List(); 90 | 91 | // adds all the active sub-nodes to a list 92 | for (int index = 0; index < 8; index++) 93 | { 94 | OctreeNode node = nodes[index]; 95 | 96 | if (node != null) 97 | { 98 | if (node.IsLeaf) 99 | { 100 | result.Add(node); 101 | } 102 | else 103 | { 104 | result.AddRange(node.ActiveNodes); 105 | } 106 | } 107 | } 108 | 109 | return result; 110 | } 111 | } 112 | 113 | public void AddColor(Color color, int level, OctreeQuantizer parent) //level - depth level 114 | { 115 | // if this node is a leaf, then increase a color amount, and pixel presence 116 | if (level == 8) 117 | { 118 | red += color.R; 119 | green += color.G; 120 | blue += color.B; 121 | pixelCount++; 122 | } 123 | else if (level < 8) // otherwise goes one level deeper 124 | { 125 | // calculates an index for the next sub-branch 126 | int index = GetColorIndexAtLevel(color, level); //current level 127 | 128 | // if that branch doesn't exist, grows it 129 | if (nodes[index] == null) 130 | { 131 | nodes[index] = new OctreeNode(level, parent); 132 | } 133 | 134 | // adds a color to that branch 135 | nodes[index].AddColor(color, level + 1, parent); 136 | } 137 | } 138 | 139 | public int GetPaletteIndex(Color color, int level) 140 | { 141 | int result; 142 | 143 | // if a node is leaf, then we've found the best match already 144 | if (IsLeaf) 145 | { 146 | result = paletteIndex; 147 | } 148 | else // otherwise continue in to the lower depths 149 | { 150 | int index = GetColorIndexAtLevel(color, level); 151 | 152 | result = nodes[index] != null ? nodes[index].GetPaletteIndex(color, level + 1) : nodes. 153 | Where(node => node != null). 154 | First(). 155 | GetPaletteIndex(color, level + 1); 156 | } 157 | 158 | return result; 159 | } 160 | 161 | public int RemoveLeaves() 162 | { 163 | int result = 0; 164 | 165 | // scans thru all the active nodes 166 | for (int index = 0; index < 8; index++) 167 | { 168 | OctreeNode node = nodes[index]; 169 | 170 | if (node != null) 171 | { 172 | // sums up their color components 173 | red += node.red; 174 | green += node.green; 175 | blue += node.blue; 176 | 177 | // and pixel presence 178 | pixelCount += node.pixelCount; 179 | 180 | // increases the count of reduced nodes 181 | result++; 182 | } 183 | } 184 | 185 | // returns a number of reduced sub-nodes, minus one because this node becomes a leaf 186 | return result - 1; 187 | } 188 | 189 | private static int GetColorIndexAtLevel(Color color, int level) 190 | { 191 | return ((color.R & Mask[level]) == Mask[level] ? 4 : 0) | 192 | ((color.G & Mask[level]) == Mask[level] ? 2 : 0) | 193 | ((color.B & Mask[level]) == Mask[level] ? 1 : 0); 194 | } 195 | 196 | internal void SetPaletteIndex(int index) 197 | { 198 | paletteIndex = index; 199 | } 200 | } 201 | 202 | 203 | 204 | public class OctreeQuantizer 205 | { 206 | 207 | private OctreeNode root; 208 | private List[] levels; 209 | 210 | public OctreeQuantizer() 211 | { 212 | Prepare(); 213 | } 214 | 215 | private void Prepare() 216 | { 217 | levels = new List[7]; 218 | // creates the octree level lists 219 | for (Int32 level = 0; level < 7; level++) 220 | { 221 | levels[level] = new List(); 222 | } 223 | root = new OctreeNode(0, this); 224 | } 225 | 226 | public void Init() 227 | { 228 | Prepare(); 229 | } 230 | 231 | public void Clear() 232 | { 233 | Prepare(); 234 | } 235 | 236 | 237 | internal IEnumerable Leaves 238 | { 239 | get { return root.ActiveNodes.Where(node => node.IsLeaf); } 240 | } 241 | 242 | internal void AddLevelNode(int level, OctreeNode octreeNode) 243 | { 244 | levels[level].Add(octreeNode); 245 | } 246 | 247 | public void AddColor(Color color) 248 | { 249 | root.AddColor(color, 0, this); 250 | } 251 | 252 | public List GetPalette(int colorCount) 253 | { 254 | List result = new List(); 255 | int leafCount = Leaves.Count(); 256 | int paletteIndex = 0; 257 | 258 | // goes thru all the levels starting at the deepest, and goes upto a root level 259 | for (int level = 6; level >= 0; level--) 260 | { 261 | // if level contains any node 262 | if (levels[level].Count > 0) 263 | { 264 | // orders the level node list by pixel presence (those with least pixels are at the top) 265 | IEnumerable sortedNodeList = levels[level].OrderBy(node => node.ActiveNodesPixelCount); 266 | 267 | // removes the nodes unless the count of the leaves is lower or equal than our requested color count 268 | foreach (OctreeNode node in sortedNodeList) 269 | { 270 | // removes a node 271 | leafCount -= node.RemoveLeaves(); 272 | 273 | // if the count of leaves is lower then our requested count terminate the loop 274 | if (leafCount <= colorCount) break; 275 | } 276 | 277 | // if the count of leaves is lower then our requested count terminate the level loop as well 278 | if (leafCount <= colorCount) break; 279 | 280 | // otherwise clear whole level, as it is not needed anymore 281 | levels[level].Clear(); 282 | } 283 | } 284 | 285 | // goes through all the leaves that are left in the tree (there should now be less or equal than requested) 286 | foreach (OctreeNode node in Leaves.OrderByDescending(node => node.ActiveNodesPixelCount)) 287 | { 288 | if (paletteIndex >= colorCount) break; 289 | 290 | // adds the leaf color to a palette 291 | if (node.IsLeaf) 292 | { 293 | result.Add(node.Color); 294 | } 295 | 296 | // and marks the node with a palette index 297 | node.SetPaletteIndex(paletteIndex++); 298 | } 299 | 300 | // we're unable to reduce the Octree with enough precision, and the leaf count is zero 301 | if (result.Count == 0) 302 | { 303 | throw new NotSupportedException("The Octree contains after the reduction 0 colors."); 304 | } 305 | 306 | // returns the palette 307 | return result; 308 | } 309 | 310 | public int GetPaletteIndex(Color color) 311 | { 312 | // retrieves a palette index 313 | return root.GetPaletteIndex(color, 0); 314 | } 315 | } 316 | } 317 | 318 | 319 | 320 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/ConstantsEditor.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace winforms_image_processor 2 | { 3 | partial class ConstantsEditor 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); 32 | this.label1 = new System.Windows.Forms.Label(); 33 | this.button1 = new System.Windows.Forms.Button(); 34 | this.button2 = new System.Windows.Forms.Button(); 35 | this.label2 = new System.Windows.Forms.Label(); 36 | this.numericUpDown2 = new System.Windows.Forms.NumericUpDown(); 37 | this.label3 = new System.Windows.Forms.Label(); 38 | this.numericUpDown3 = new System.Windows.Forms.NumericUpDown(); 39 | this.label4 = new System.Windows.Forms.Label(); 40 | this.numericUpDown4 = new System.Windows.Forms.NumericUpDown(); 41 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); 42 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).BeginInit(); 43 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDown3)).BeginInit(); 44 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDown4)).BeginInit(); 45 | this.SuspendLayout(); 46 | // 47 | // numericUpDown1 48 | // 49 | this.numericUpDown1.DecimalPlaces = 4; 50 | this.numericUpDown1.Location = new System.Drawing.Point(152, 22); 51 | this.numericUpDown1.Maximum = new decimal(new int[] { 52 | 10000, 53 | 0, 54 | 0, 55 | 0}); 56 | this.numericUpDown1.Minimum = new decimal(new int[] { 57 | 1, 58 | 0, 59 | 0, 60 | 262144}); 61 | this.numericUpDown1.Name = "numericUpDown1"; 62 | this.numericUpDown1.Size = new System.Drawing.Size(120, 20); 63 | this.numericUpDown1.TabIndex = 0; 64 | this.numericUpDown1.Value = new decimal(new int[] { 65 | 1, 66 | 0, 67 | 0, 68 | 262144}); 69 | // 70 | // label1 71 | // 72 | this.label1.AutoSize = true; 73 | this.label1.Location = new System.Drawing.Point(12, 24); 74 | this.label1.Name = "label1"; 75 | this.label1.Size = new System.Drawing.Size(91, 13); 76 | this.label1.TabIndex = 1; 77 | this.label1.Text = "Gamma Exponent"; 78 | // 79 | // button1 80 | // 81 | this.button1.Location = new System.Drawing.Point(44, 191); 82 | this.button1.Name = "button1"; 83 | this.button1.Size = new System.Drawing.Size(75, 23); 84 | this.button1.TabIndex = 2; 85 | this.button1.Text = "Save"; 86 | this.button1.UseVisualStyleBackColor = true; 87 | this.button1.Click += new System.EventHandler(this.button1_Click); 88 | // 89 | // button2 90 | // 91 | this.button2.Location = new System.Drawing.Point(161, 191); 92 | this.button2.Name = "button2"; 93 | this.button2.Size = new System.Drawing.Size(75, 23); 94 | this.button2.TabIndex = 3; 95 | this.button2.Text = "Cancel"; 96 | this.button2.UseVisualStyleBackColor = true; 97 | this.button2.Click += new System.EventHandler(this.button2_Click); 98 | // 99 | // label2 100 | // 101 | this.label2.AutoSize = true; 102 | this.label2.Location = new System.Drawing.Point(12, 47); 103 | this.label2.Name = "label2"; 104 | this.label2.Size = new System.Drawing.Size(56, 13); 105 | this.label2.TabIndex = 5; 106 | this.label2.Text = "Brightness"; 107 | // 108 | // numericUpDown2 109 | // 110 | this.numericUpDown2.DecimalPlaces = 4; 111 | this.numericUpDown2.Location = new System.Drawing.Point(152, 45); 112 | this.numericUpDown2.Maximum = new decimal(new int[] { 113 | 10000, 114 | 0, 115 | 0, 116 | 0}); 117 | this.numericUpDown2.Minimum = new decimal(new int[] { 118 | 10000, 119 | 0, 120 | 0, 121 | -2147483648}); 122 | this.numericUpDown2.Name = "numericUpDown2"; 123 | this.numericUpDown2.Size = new System.Drawing.Size(120, 20); 124 | this.numericUpDown2.TabIndex = 4; 125 | this.numericUpDown2.Value = new decimal(new int[] { 126 | 1, 127 | 0, 128 | 0, 129 | 262144}); 130 | // 131 | // label3 132 | // 133 | this.label3.AutoSize = true; 134 | this.label3.Location = new System.Drawing.Point(12, 70); 135 | this.label3.Name = "label3"; 136 | this.label3.Size = new System.Drawing.Size(46, 13); 137 | this.label3.TabIndex = 7; 138 | this.label3.Text = "Contrast"; 139 | // 140 | // numericUpDown3 141 | // 142 | this.numericUpDown3.DecimalPlaces = 4; 143 | this.numericUpDown3.Location = new System.Drawing.Point(152, 68); 144 | this.numericUpDown3.Maximum = new decimal(new int[] { 145 | 10000, 146 | 0, 147 | 0, 148 | 0}); 149 | this.numericUpDown3.Minimum = new decimal(new int[] { 150 | 10000, 151 | 0, 152 | 0, 153 | -2147483648}); 154 | this.numericUpDown3.Name = "numericUpDown3"; 155 | this.numericUpDown3.Size = new System.Drawing.Size(120, 20); 156 | this.numericUpDown3.TabIndex = 6; 157 | this.numericUpDown3.Value = new decimal(new int[] { 158 | 1, 159 | 0, 160 | 0, 161 | 262144}); 162 | // 163 | // label4 164 | // 165 | this.label4.AutoSize = true; 166 | this.label4.Location = new System.Drawing.Point(12, 93); 167 | this.label4.Name = "label4"; 168 | this.label4.Size = new System.Drawing.Size(133, 13); 169 | this.label4.TabIndex = 9; 170 | this.label4.Text = "Octree Quantization Colors"; 171 | // 172 | // numericUpDown4 173 | // 174 | this.numericUpDown4.DecimalPlaces = 4; 175 | this.numericUpDown4.Location = new System.Drawing.Point(152, 91); 176 | this.numericUpDown4.Maximum = new decimal(new int[] { 177 | 1000000, 178 | 0, 179 | 0, 180 | 0}); 181 | this.numericUpDown4.Minimum = new decimal(new int[] { 182 | 8, 183 | 0, 184 | 0, 185 | 0}); 186 | this.numericUpDown4.Name = "numericUpDown4"; 187 | this.numericUpDown4.Size = new System.Drawing.Size(120, 20); 188 | this.numericUpDown4.TabIndex = 8; 189 | this.numericUpDown4.Value = new decimal(new int[] { 190 | 8, 191 | 0, 192 | 0, 193 | 0}); 194 | // 195 | // ConstantsEditor 196 | // 197 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 198 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 199 | this.ClientSize = new System.Drawing.Size(284, 261); 200 | this.Controls.Add(this.label4); 201 | this.Controls.Add(this.numericUpDown4); 202 | this.Controls.Add(this.label3); 203 | this.Controls.Add(this.numericUpDown3); 204 | this.Controls.Add(this.label2); 205 | this.Controls.Add(this.numericUpDown2); 206 | this.Controls.Add(this.button2); 207 | this.Controls.Add(this.button1); 208 | this.Controls.Add(this.label1); 209 | this.Controls.Add(this.numericUpDown1); 210 | this.Name = "ConstantsEditor"; 211 | this.Text = "ConstantsEditor"; 212 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); 213 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).EndInit(); 214 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDown3)).EndInit(); 215 | ((System.ComponentModel.ISupportInitialize)(this.numericUpDown4)).EndInit(); 216 | this.ResumeLayout(false); 217 | this.PerformLayout(); 218 | 219 | } 220 | 221 | #endregion 222 | 223 | private System.Windows.Forms.NumericUpDown numericUpDown1; 224 | private System.Windows.Forms.Label label1; 225 | private System.Windows.Forms.Button button1; 226 | private System.Windows.Forms.Button button2; 227 | private System.Windows.Forms.Label label2; 228 | private System.Windows.Forms.NumericUpDown numericUpDown2; 229 | private System.Windows.Forms.Label label3; 230 | private System.Windows.Forms.NumericUpDown numericUpDown3; 231 | private System.Windows.Forms.Label label4; 232 | private System.Windows.Forms.NumericUpDown numericUpDown4; 233 | } 234 | } -------------------------------------------------------------------------------- /winforms-image-processor/Forms/ConstantsEditor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Windows.Forms; 3 | 4 | namespace winforms_image_processor 5 | { 6 | public partial class ConstantsEditor : Form 7 | { 8 | public ConstantsEditor() 9 | { 10 | InitializeComponent(); 11 | 12 | numericUpDown1.Value = (decimal)Constants.filterGammaValue; 13 | numericUpDown2.Value = (decimal)Constants.filterBrightnessValue; 14 | numericUpDown3.Value = (decimal)Constants.filterContrastValue; 15 | numericUpDown4.Value = Constants.filterOctreeColorLimit; 16 | } 17 | 18 | private void button1_Click(object sender, EventArgs e) 19 | { 20 | Constants.filterGammaValue = (double)numericUpDown1.Value; 21 | Constants.filterBrightnessValue = (double)numericUpDown2.Value; 22 | Constants.filterContrastValue = (double)numericUpDown3.Value; 23 | Constants.filterOctreeColorLimit = (int)numericUpDown4.Value; 24 | 25 | DialogResult = DialogResult.OK; 26 | Close(); 27 | } 28 | 29 | private void button2_Click(object sender, EventArgs e) 30 | { 31 | DialogResult = DialogResult.Cancel; 32 | Close(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/ConstantsEditor.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/DrawForm.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Windows; 10 | using System.Windows.Forms; 11 | 12 | namespace winforms_image_processor 13 | { 14 | public enum DrawingShape { EMPTY, LINE, CIRCLE, POLY, CAPS, RECT, CPOLY, FILL }; 15 | 16 | public partial class DrawForm : Form 17 | { 18 | 19 | public DrawForm() 20 | { 21 | InitializeComponent(); 22 | 23 | listBox1.DataSource = shapes; 24 | } 25 | 26 | BindingList shapes = new BindingList(); 27 | 28 | private void newToolStripMenuItem_Click(object sender, EventArgs e) 29 | { 30 | shapes.Clear(); 31 | 32 | pictureBox1.Image = NewBitmap(); 33 | 34 | toolsToolStripMenuItem.Enabled = true; 35 | } 36 | 37 | Color backColor = Color.Green; 38 | Bitmap NewBitmap() 39 | { 40 | var bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height); 41 | 42 | Graphics g = Graphics.FromImage(bmp); 43 | g.Clear(backColor); 44 | 45 | return bmp; 46 | } 47 | 48 | private void DrawForm_ResizeEnd(object sender, EventArgs e) 49 | { 50 | if (pictureBox1.Width <= 0 || pictureBox1.Height <= 0) 51 | return; 52 | pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height); 53 | RefreshShapes(); 54 | } 55 | 56 | void UpdateLabel() 57 | { 58 | StringBuilder sb; 59 | if (currentShape == null) 60 | sb = new StringBuilder(); 61 | else 62 | { 63 | sb = new StringBuilder("Currently drawing: "); 64 | sb.AppendLine(currentShape.ToString()); 65 | sb.Append(currentShape.howToDraw()); 66 | } 67 | 68 | label1.Text = sb.ToString(); 69 | } 70 | 71 | void RefreshShapes() 72 | { 73 | Bitmap bmp = NewBitmap(); 74 | foreach (var shape in shapes) 75 | { 76 | if (shape.shapeType == DrawingShape.FILL) 77 | bmp = FloodFiller.FourWayFloodFill(bmp, shape.shapeColor, ((Fill)shape).seedPoint); 78 | else 79 | DrawShape(bmp, shape); 80 | } 81 | 82 | pictureBox1.Image = bmp; 83 | } 84 | 85 | Bitmap DrawShape(Bitmap bmp, Shape shape) 86 | { 87 | if (!antialiasingToolStripMenuItem.Checked || !shape.supportsAA) 88 | foreach (var point in shape.GetPixels(showClipBorderToolStripMenuItem.Checked, colorDialog2.Color, bmp)) 89 | { 90 | if (point.Point.X >= pictureBox1.Width || point.Point.Y >= pictureBox1.Height || point.Point.X <= 0 || point.Point.Y <= 0) 91 | continue; 92 | 93 | bmp.SetPixelFast(point.Point.X, point.Point.Y, point.Color); 94 | } 95 | else 96 | { 97 | foreach (var point in shape.GetPixelsAA(bmp)) 98 | { 99 | if (point.Point.X >= pictureBox1.Width || point.Point.Y >= pictureBox1.Height || point.Point.X <= 0 || point.Point.Y <= 0) 100 | continue; 101 | 102 | bmp.SetPixelFast(point.Point.X, point.Point.Y, point.Color); 103 | } 104 | } 105 | 106 | return bmp; 107 | } 108 | 109 | Shape currentShape = null; 110 | DrawingShape currentDrawingShape = DrawingShape.EMPTY; 111 | 112 | bool canRefresh = true; 113 | 114 | bool drawing = false; 115 | bool moving = false; 116 | bool clipping = false; 117 | int index; 118 | 119 | void drawMode( 120 | bool status, 121 | Shape shape = null, 122 | int modify_index = -1 123 | ) 124 | { 125 | if (!status && index == -1) 126 | { 127 | shapes.Add(currentShape); 128 | if (shapes.Count == 1) 129 | listBox1_SelectedIndexChanged(null, null); 130 | RefreshShapes(); 131 | } 132 | else if (!status) 133 | { 134 | shapes[index] = currentShape; 135 | RefreshShapes(); 136 | } 137 | 138 | splitContainer2.Panel1.Enabled = !status; 139 | 140 | index = modify_index; 141 | drawing = status; 142 | currentDrawingShape = shape == null ? DrawingShape.EMPTY : shape.shapeType; 143 | currentShape = shape; 144 | UpdateLabel(); 145 | } 146 | 147 | private void pictureBox1_MouseClick(object sender, MouseEventArgs e) 148 | { 149 | if (drawing) 150 | { 151 | if (currentShape.shapeType == DrawingShape.POLY) 152 | { 153 | if (1 == ((Polygon)currentShape).AddPoint(e.Location, out MidPointLine line)) 154 | drawMode(false); 155 | 156 | if (line != null) 157 | pictureBox1.Image = DrawShape((Bitmap)pictureBox1.Image, line); 158 | 159 | return; 160 | } 161 | 162 | if (1 == currentShape.AddPoint(e.Location)) 163 | drawMode(false); 164 | } 165 | 166 | if (clipping) 167 | { 168 | if (1 == currentShape.AddPoint(e.Location)) 169 | clipMode(false, null); 170 | } 171 | 172 | if (flooding) 173 | { 174 | shapes.Add(new Fill(colorDialog1.Color, e.Location)); 175 | flooding = false; 176 | RefreshShapes(); 177 | } 178 | } 179 | 180 | private void midpointCircleToolStripMenuItem_Click(object sender, EventArgs e) 181 | { 182 | drawMode(true, new MidPointCircle(colorDialog1.Color)); 183 | } 184 | 185 | private void midpointLineToolStripMenuItem_Click(object sender, EventArgs e) 186 | { 187 | drawMode(true, new MidPointLine(colorDialog1.Color, (int)numericUpDown1.Value)); 188 | } 189 | 190 | private void polygonToolStripMenuItem_Click(object sender, EventArgs e) 191 | { 192 | drawMode(true, new Polygon(colorDialog1.Color, (int)numericUpDown1.Value)); 193 | } 194 | 195 | private void capsuleToolStripMenuItem_Click(object sender, EventArgs e) 196 | { 197 | drawMode(true, new Capsule(colorDialog1.Color)); 198 | } 199 | 200 | private void rectangleToolStripMenuItem_Click(object sender, EventArgs e) 201 | { 202 | drawMode(true, new Rectangle(colorDialog1.Color, (int)numericUpDown1.Value)); 203 | } 204 | 205 | bool flooding = false; 206 | 207 | private void floodFillToolStripMenuItem1_Click(object sender, EventArgs e) 208 | { 209 | flooding = true; 210 | } 211 | 212 | void clipMode(bool status, Shape shape, int modify_index = -1) 213 | { 214 | if (!status && shapes[index].shapeType == DrawingShape.POLY) 215 | { 216 | ClippedPolygon cpoly = new ClippedPolygon((Polygon)shapes[index]); 217 | cpoly.SetBoundingRect((Rectangle)currentShape); 218 | shapes[index] = cpoly; 219 | RefreshShapes(); 220 | } 221 | else if (!status && shapes[index].shapeType == DrawingShape.CPOLY) 222 | { 223 | ((ClippedPolygon)shapes[index]).SetBoundingRect((Rectangle)currentShape); 224 | RefreshShapes(); 225 | } 226 | 227 | splitContainer2.Panel1.Enabled = !status; 228 | 229 | index = modify_index; 230 | clipping = status; 231 | 232 | currentDrawingShape = shape == null ? DrawingShape.EMPTY : shape.shapeType; 233 | currentShape = shape; 234 | UpdateLabel(); 235 | } 236 | 237 | private void button4_Click(object sender, EventArgs e) 238 | { 239 | clipMode(true, new Rectangle(Color.Transparent, 1), listBox1.SelectedIndex); 240 | } 241 | 242 | private void button5_Click(object sender, EventArgs e) 243 | { 244 | if (shapes.Count < 1) 245 | return; 246 | 247 | if ((listBox1.SelectedItem as Shape).shapeType != DrawingShape.POLY && (listBox1.SelectedItem as Shape).shapeType != DrawingShape.CPOLY) 248 | return; 249 | 250 | FillMenu fillMenuForm = new FillMenu(); 251 | 252 | switch (fillMenuForm.ShowDialog()) 253 | { 254 | case DialogResult.Yes: 255 | (listBox1.SelectedItem as Polygon).SetFiller(fillMenuForm.FillColor); 256 | break; 257 | case DialogResult.No: 258 | (listBox1.SelectedItem as Polygon).SetFiller(fillMenuForm.filename); 259 | break; 260 | case DialogResult.Cancel: 261 | default: 262 | break; 263 | } 264 | 265 | RefreshShapes(); 266 | } 267 | 268 | private void button1_Click(object sender, EventArgs e) 269 | { 270 | if (colorDialog1.ShowDialog() == DialogResult.OK) 271 | { 272 | button1.BackColor = colorDialog1.Color; 273 | } 274 | } 275 | 276 | private void button2_Click(object sender, EventArgs e) 277 | { 278 | if (shapes.Count == 0) 279 | return; 280 | 281 | switch (shapes[listBox1.SelectedIndex].shapeType) 282 | { 283 | case DrawingShape.CIRCLE: 284 | drawMode(true, new MidPointCircle(colorDialog1.Color), listBox1.SelectedIndex); 285 | break; 286 | case DrawingShape.LINE: 287 | drawMode(true, new MidPointLine(colorDialog1.Color, (int)numericUpDown1.Value), listBox1.SelectedIndex); 288 | break; 289 | case DrawingShape.POLY: 290 | case DrawingShape.CPOLY: 291 | drawMode(true, new Polygon(colorDialog1.Color, (int)numericUpDown1.Value), listBox1.SelectedIndex); 292 | break; 293 | case DrawingShape.CAPS: 294 | drawMode(true, new Capsule(colorDialog1.Color), listBox1.SelectedIndex); 295 | break; 296 | case DrawingShape.RECT: 297 | drawMode(true, new Rectangle(colorDialog1.Color, (int)numericUpDown1.Value), listBox1.SelectedIndex); 298 | break; 299 | 300 | default: 301 | case DrawingShape.EMPTY: 302 | break; 303 | } 304 | } 305 | 306 | private void button3_Click(object sender, EventArgs e) 307 | { 308 | if (shapes.Count == 0) 309 | return; 310 | 311 | shapes.RemoveAt(listBox1.SelectedIndex); 312 | 313 | listBox1_SelectedIndexChanged(null, null); 314 | 315 | RefreshShapes(); 316 | } 317 | 318 | private void saveToolStripMenuItem_Click(object sender, EventArgs e) 319 | { 320 | SaveFileDialog saveFileDialog1 = new SaveFileDialog(); 321 | 322 | saveFileDialog1.InitialDirectory = "c:\\Downloads"; 323 | saveFileDialog1.Filter = "Vector shapes (*.cg2020)|*.cg2020"; 324 | saveFileDialog1.DefaultExt = "dat"; 325 | saveFileDialog1.AddExtension = true; 326 | saveFileDialog1.Title = "Save the filtered image"; 327 | saveFileDialog1.ShowDialog(); 328 | 329 | if (saveFileDialog1.FileName != "") 330 | { 331 | ShapeSerializer.Save(saveFileDialog1.FileName, shapes); 332 | } 333 | } 334 | 335 | private void openToolStripMenuItem_Click(object sender, EventArgs e) 336 | { 337 | if (pictureBox1.Image == null) 338 | pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height); 339 | 340 | var filePath = string.Empty; 341 | 342 | using (OpenFileDialog openFileDialog = new OpenFileDialog()) 343 | { 344 | openFileDialog.InitialDirectory = "c:\\Downloads"; 345 | openFileDialog.Filter = "Vector shapes (*.cg2020)|*.cg2020"; 346 | openFileDialog.FilterIndex = 2; 347 | openFileDialog.RestoreDirectory = true; 348 | 349 | if (openFileDialog.ShowDialog() == DialogResult.OK) 350 | { 351 | shapes.Clear(); 352 | foreach (var shape in ShapeSerializer.Load(openFileDialog.FileName)) 353 | shapes.Add(shape); 354 | } 355 | else 356 | return; 357 | } 358 | 359 | RefreshShapes(); 360 | } 361 | 362 | private void antialiasingToolStripMenuItem_CheckedChanged(object sender, EventArgs e) 363 | { 364 | if (pictureBox1.Image == null) 365 | return; 366 | RefreshShapes(); 367 | } 368 | 369 | private void backgroundColorToolStripMenuItem_Click(object sender, EventArgs e) 370 | { 371 | if (colorDialog2.ShowDialog() == DialogResult.OK) 372 | { 373 | backColor = colorDialog2.Color; 374 | RefreshShapes(); 375 | } 376 | } 377 | 378 | private void checkBox1_CheckedChanged(object sender, EventArgs e) 379 | { 380 | moving = true; 381 | } 382 | 383 | System.Drawing.Point movestart; 384 | System.Drawing.Point moveend; 385 | 386 | private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 387 | { 388 | if (!moving) 389 | return; 390 | 391 | movestart = e.Location; 392 | splitContainer2.Panel1.Enabled = false; 393 | checkBox1.Checked = false; 394 | 395 | } 396 | 397 | private void pictureBox1_MouseUp(object sender, MouseEventArgs e) 398 | { 399 | if (!moving) 400 | return; 401 | 402 | moveend = e.Location; 403 | 404 | moving = false; 405 | checkBox1.Checked = false; 406 | 407 | splitContainer2.Panel1.Enabled = true; 408 | 409 | ((Shape)listBox1.SelectedItem).MovePoints(moveend - (System.Drawing.Size)movestart); 410 | 411 | RefreshShapes(); 412 | } 413 | 414 | private void showClipBorderToolStripMenuItem_Click(object sender, EventArgs e) 415 | { 416 | RefreshShapes(); 417 | } 418 | 419 | private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 420 | { 421 | if (shapes.Count < 1) 422 | { 423 | button4.Enabled = false; 424 | button5.Enabled = false; 425 | return; 426 | } 427 | 428 | if (listBox1.SelectedIndex == -1) 429 | { 430 | button4.Enabled = false; 431 | button5.Enabled = false; 432 | return; 433 | } 434 | 435 | button4.Enabled = (((Shape)listBox1.SelectedItem).shapeType == DrawingShape.POLY || ((Shape)listBox1.SelectedItem).shapeType == DrawingShape.CPOLY) ? true : false; 436 | button5.Enabled = (((Shape)listBox1.SelectedItem).shapeType == DrawingShape.POLY || ((Shape)listBox1.SelectedItem).shapeType == DrawingShape.CPOLY) ? true : false; 437 | } 438 | 439 | private void selectColorToolStripMenuItem_Click(object sender, EventArgs e) 440 | { 441 | colorDialog3.ShowDialog(); 442 | } 443 | 444 | 445 | } 446 | } 447 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/DrawForm.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 17, 17 122 | 123 | 124 | 132, 17 125 | 126 | 127 | 253, 17 128 | 129 | 130 | 374, 17 131 | 132 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/FillMenu.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace winforms_image_processor 2 | { 3 | partial class FillMenu 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.button1 = new System.Windows.Forms.Button(); 32 | this.button2 = new System.Windows.Forms.Button(); 33 | this.button3 = new System.Windows.Forms.Button(); 34 | this.label1 = new System.Windows.Forms.Label(); 35 | this.colorDialog1 = new System.Windows.Forms.ColorDialog(); 36 | this.SuspendLayout(); 37 | // 38 | // button1 39 | // 40 | this.button1.Location = new System.Drawing.Point(12, 45); 41 | this.button1.Name = "button1"; 42 | this.button1.Size = new System.Drawing.Size(57, 23); 43 | this.button1.TabIndex = 0; 44 | this.button1.Text = "Color"; 45 | this.button1.UseVisualStyleBackColor = true; 46 | this.button1.Click += new System.EventHandler(this.button1_Click); 47 | // 48 | // button2 49 | // 50 | this.button2.Location = new System.Drawing.Point(75, 45); 51 | this.button2.Name = "button2"; 52 | this.button2.Size = new System.Drawing.Size(57, 23); 53 | this.button2.TabIndex = 1; 54 | this.button2.Text = "Image"; 55 | this.button2.UseVisualStyleBackColor = true; 56 | this.button2.Click += new System.EventHandler(this.button2_Click); 57 | // 58 | // button3 59 | // 60 | this.button3.Location = new System.Drawing.Point(138, 45); 61 | this.button3.Name = "button3"; 62 | this.button3.Size = new System.Drawing.Size(57, 23); 63 | this.button3.TabIndex = 2; 64 | this.button3.Text = "Cancel"; 65 | this.button3.UseVisualStyleBackColor = true; 66 | this.button3.Click += new System.EventHandler(this.button3_Click); 67 | // 68 | // label1 69 | // 70 | this.label1.AutoSize = true; 71 | this.label1.Location = new System.Drawing.Point(31, 17); 72 | this.label1.Name = "label1"; 73 | this.label1.Size = new System.Drawing.Size(88, 13); 74 | this.label1.TabIndex = 3; 75 | this.label1.Text = "Select fill material"; 76 | // 77 | // FillMenu 78 | // 79 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 80 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 81 | this.ClientSize = new System.Drawing.Size(227, 91); 82 | this.Controls.Add(this.label1); 83 | this.Controls.Add(this.button3); 84 | this.Controls.Add(this.button2); 85 | this.Controls.Add(this.button1); 86 | this.Name = "FillMenu"; 87 | this.Text = "FillMenu"; 88 | this.ResumeLayout(false); 89 | this.PerformLayout(); 90 | 91 | } 92 | 93 | #endregion 94 | 95 | private System.Windows.Forms.Button button1; 96 | private System.Windows.Forms.Button button2; 97 | private System.Windows.Forms.Button button3; 98 | private System.Windows.Forms.Label label1; 99 | private System.Windows.Forms.ColorDialog colorDialog1; 100 | } 101 | } -------------------------------------------------------------------------------- /winforms-image-processor/Forms/FillMenu.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Runtime.Remoting.Messaging; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using System.Windows.Forms; 11 | 12 | namespace winforms_image_processor 13 | { 14 | public partial class FillMenu : Form 15 | { 16 | public FillMenu() 17 | { 18 | InitializeComponent(); 19 | } 20 | 21 | 22 | public Color FillColor 23 | { 24 | get { return colorDialog1.Color; } 25 | } 26 | public string filename; 27 | private void button1_Click(object sender, EventArgs e) 28 | { 29 | if (colorDialog1.ShowDialog() == DialogResult.OK) 30 | { 31 | DialogResult = DialogResult.Yes; 32 | Close(); 33 | } 34 | } 35 | 36 | private void button2_Click(object sender, EventArgs e) 37 | { 38 | using (OpenFileDialog openFileDialog = new OpenFileDialog()) 39 | { 40 | openFileDialog.InitialDirectory = "c:\\Downloads"; 41 | openFileDialog.Filter = "JPEG Image|*.jpg|PNG Image|*.png"; 42 | openFileDialog.FilterIndex = 2; 43 | openFileDialog.RestoreDirectory = true; 44 | 45 | if (openFileDialog.ShowDialog() == DialogResult.OK) 46 | { 47 | filename = openFileDialog.FileName; 48 | DialogResult = DialogResult.No; 49 | Close(); 50 | } 51 | else 52 | return; 53 | } 54 | } 55 | 56 | private void button3_Click(object sender, EventArgs e) 57 | { 58 | DialogResult = DialogResult.Cancel; 59 | Close(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/FillMenu.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 17, 17 122 | 123 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/ImageProcessorForm.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Drawing; 5 | using System.Windows.Forms; 6 | 7 | namespace winforms_image_processor 8 | { 9 | public partial class ImageProcessorForm : Form 10 | { 11 | public ImageProcessorForm() 12 | { 13 | InitializeComponent(); 14 | 15 | foreach (var filter in FilterManager.filterMapping) 16 | { 17 | ToolStripMenuItem subItem = new ToolStripMenuItem(filter.Key); 18 | ToolStripMenuItem subsubItem = new ToolStripMenuItem("Add layer"); 19 | subItem.DropDownItems.Add(subsubItem); 20 | subsubItem.Click += AddMultipleLayer; 21 | 22 | subItem.DropDown.Closing += new ToolStripDropDownClosingEventHandler(dropDownClosing); 23 | 24 | filtersToolStripMenuItem.DropDownItems.Add(subItem); 25 | } 26 | 27 | FltPictureBox.ContextMenuStrip = contextMenuStrip1; 28 | } 29 | 30 | private void dropDownClosing(object sender, ToolStripDropDownClosingEventArgs e) 31 | { 32 | if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) 33 | { 34 | e.Cancel = true; 35 | } 36 | } 37 | 38 | Dictionary multipleFilterCount = new Dictionary(); 39 | 40 | private void AddMultipleLayer(object sender, EventArgs e) 41 | { 42 | ToolStripMenuItem ts = sender as ToolStripMenuItem; 43 | ToolStripMenuItem tsParent = ts.OwnerItem as ToolStripMenuItem; 44 | 45 | if (!multipleFilterCount.ContainsKey(tsParent.Text)) 46 | multipleFilterCount.Add(tsParent.Text, 1); 47 | else 48 | multipleFilterCount[tsParent.Text] += 1; 49 | 50 | ToolStripMenuItem tsLayer = new ToolStripMenuItem(tsParent.Text); 51 | tsLayer.CheckedChanged += StateChange; 52 | tsLayer.CheckOnClick = true; 53 | tsParent.DropDownItems.Add(tsLayer); 54 | } 55 | 56 | private void StateChange(object sender, EventArgs e) 57 | { 58 | ToolStripMenuItem tsmi = sender as ToolStripMenuItem; 59 | CacheManager.UpdateFilterState(sender.ToString(), tsmi.Checked); 60 | 61 | Debug.Print( 62 | "Cache for state [ " + String.Join(" -> ", CacheManager.filterState.ToArray()) 63 | + " ] is " + (CacheManager.GetBitmapForFilterState() == null ? "null" : "not null") 64 | ); 65 | 66 | UpdateCacheIfEmpty(); 67 | 68 | FltPictureBox.Image = CacheManager.GetBitmapForFilterState(); 69 | 70 | if (yBRColorspaceDisplay != null) 71 | yBRColorspaceDisplay.updateImages((Bitmap)FltPictureBox.Image); 72 | } 73 | 74 | public void UpdateCacheIfEmpty() 75 | { 76 | if (CacheManager.GetBitmapForFilterState() == null) 77 | CacheManager.SetBitmapForFilterState( 78 | FilterManager.RecreateFilterStateFromState( 79 | CacheManager.GetOriginalImage(), CacheManager.filterState 80 | ) 81 | ); 82 | } 83 | 84 | private void OpenImageFileMenu_Click(object sender, EventArgs e) 85 | // File Dialog: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.openfiledialog?view=netframework-4.8 86 | // Bitmap deep copy: https://stackoverflow.com/questions/16316451/how-can-i-open-a-bitmap-file-change-it-and-then-save-it 87 | // PictureBox Bitmap: https://stackoverflow.com/questions/743549/how-to-put-image-in-a-picture-box-from-bitmap 88 | { 89 | var filePath = string.Empty; 90 | 91 | using (OpenFileDialog openFileDialog = new OpenFileDialog()) 92 | { 93 | openFileDialog.InitialDirectory = "c:\\Downloads"; 94 | openFileDialog.Filter = "JPEG Image|*.jpg|PNG Image|*.png"; 95 | openFileDialog.FilterIndex = 2; 96 | openFileDialog.RestoreDirectory = true; 97 | 98 | if (openFileDialog.ShowDialog() == DialogResult.OK) 99 | filePath = openFileDialog.FileName; 100 | else 101 | return; 102 | } 103 | 104 | OrgPictureBox.Image = new Bitmap(filePath); 105 | FltPictureBox.Image = new Bitmap(filePath); 106 | 107 | viewToolStripMenuItem.Enabled = true; 108 | filtersToolStripMenuItem.Enabled = true; 109 | SaveImageFileMenu.Enabled = true; 110 | customKernelToolStripMenuItem.Enabled = true; 111 | yBRSplitToolStripMenuItem.Enabled = true; 112 | 113 | if (CacheManager.cachedFilterStates != null) 114 | { 115 | CacheManager.ResetCache((Bitmap)OrgPictureBox.Image); 116 | UpdateCacheIfEmpty(); 117 | 118 | FltPictureBox.Image = CacheManager.GetBitmapForFilterState(); 119 | } 120 | else 121 | CacheManager.InitializeWithOriginal((Bitmap)FltPictureBox.Image); 122 | } 123 | 124 | private void SaveImageFileMenu_Click(object sender, EventArgs e) 125 | // SaveFileControl: https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-save-files-using-the-savefiledialog-component 126 | { 127 | SaveFileDialog saveFileDialog1 = new SaveFileDialog(); 128 | saveFileDialog1.Filter = "JPEG Image|*.jpg|PNG Image|*.png"; 129 | saveFileDialog1.Title = "Save the filtered image"; 130 | saveFileDialog1.ShowDialog(); 131 | 132 | if (saveFileDialog1.FileName != "") 133 | { 134 | Bitmap filteredImage = (Bitmap)FltPictureBox.Image; 135 | filteredImage.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Png); 136 | } 137 | } 138 | 139 | private void customKernelToolStripMenuItem_Click(object sender, EventArgs e) 140 | { 141 | //KernelEditor kernelEditor = new KernelEditor(this); 142 | //if (kernelEditor.ShowDialog() == DialogResult.Cancel) return; 143 | 144 | //CacheManager.ResetCache((Bitmap)OrgPictureBox.Image); 145 | //UpdateCacheIfEmpty(); 146 | 147 | //FltPictureBox.Image = CacheManager.GetBitmapForFilterState(); 148 | } 149 | 150 | public void OpenKernelEditor(object sender, EventArgs e) 151 | { 152 | ToolStripMenuItem ts = sender as ToolStripMenuItem; 153 | KernelEditor kernelEditor = new KernelEditor(this, ts.OwnerItem.Text); 154 | if (kernelEditor.ShowDialog() == DialogResult.Cancel) return; 155 | 156 | CacheManager.ResetCache((Bitmap)OrgPictureBox.Image); 157 | UpdateCacheIfEmpty(); 158 | 159 | FltPictureBox.Image = CacheManager.GetBitmapForFilterState(); 160 | } 161 | 162 | private void copyToolStripMenuItem_Click(object sender, EventArgs e) 163 | { 164 | Clipboard.SetImage(FltPictureBox.Image); 165 | } 166 | 167 | static public int customKernelCounter = 0; 168 | 169 | private void addToolStripMenuItem_Click(object sender, EventArgs e) 170 | { 171 | string name = "Custom Kernel " + ++customKernelCounter; 172 | ToolStripMenuItem ts = new ToolStripMenuItem(name); 173 | 174 | ToolStripMenuItem tsEdit = new ToolStripMenuItem("Edit"); 175 | 176 | tsEdit.Click += OpenKernelEditor; 177 | 178 | ts.CheckOnClick = true; 179 | ts.CheckedChanged += StateChange; 180 | 181 | ts.DropDownItems.Add(tsEdit); 182 | 183 | Kernel.customKernels.Add(name, new CustomKernel(new double[3, 3] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } }, 1, 0, Point.Empty)); 184 | 185 | FilterManager.UpdateFilterMapping(name); 186 | 187 | filtersToolStripMenuItem.DropDownItems.Add(ts); 188 | } 189 | 190 | private void editFilterConstantsToolStripMenuItem_Click(object sender, EventArgs e) 191 | { 192 | ConstantsEditor constantsEditor = new ConstantsEditor(); 193 | if (constantsEditor.ShowDialog() == DialogResult.Cancel) return; 194 | 195 | CacheManager.ResetCache((Bitmap)OrgPictureBox.Image); 196 | UpdateCacheIfEmpty(); 197 | 198 | FltPictureBox.Image = CacheManager.GetBitmapForFilterState(); 199 | } 200 | 201 | private void fitToolStripMenuItem_Click(object sender, EventArgs e) 202 | { 203 | if (OrgPictureBox.SizeMode == PictureBoxSizeMode.Zoom) return; 204 | 205 | OrgPictureBox.SizeMode = PictureBoxSizeMode.Zoom; 206 | FltPictureBox.SizeMode = PictureBoxSizeMode.Zoom; 207 | } 208 | 209 | private void originalSizeToolStripMenuItem_Click(object sender, EventArgs e) 210 | { 211 | if (OrgPictureBox.SizeMode == PictureBoxSizeMode.AutoSize) return; 212 | 213 | OrgPictureBox.SizeMode = PictureBoxSizeMode.AutoSize; 214 | FltPictureBox.SizeMode = PictureBoxSizeMode.AutoSize; 215 | } 216 | 217 | private void resetToolStripMenuItem_Click(object sender, EventArgs e) 218 | { 219 | CacheManager.filterState = new List(); 220 | FltPictureBox.Image = CacheManager.GetOriginalImage(); 221 | UncheckToolsRecursion(filtersToolStripMenuItem); 222 | } 223 | 224 | private void UncheckToolsRecursion(ToolStripMenuItem tsmi) 225 | //Recursion for toolstrip: https://stackoverflow.com/questions/33766276/cannot-get-all-the-submenu-items-in-winform-in-c-sharp 226 | { 227 | if (tsmi.Checked) 228 | tsmi.Checked = false; 229 | 230 | foreach (ToolStripMenuItem innerTsmi in tsmi.DropDownItems) 231 | { 232 | UncheckToolsRecursion(innerTsmi); 233 | } 234 | } 235 | 236 | public YBRColorspaceDisplay yBRColorspaceDisplay; 237 | 238 | private void yBRSplitToolStripMenuItem_Click(object sender, EventArgs e) 239 | { 240 | yBRColorspaceDisplay = new YBRColorspaceDisplay(this, (Bitmap)FltPictureBox.Image); 241 | 242 | yBRColorspaceDisplay.Show(); 243 | } 244 | 245 | private void drawingToolsToolStripMenuItem_Click(object sender, EventArgs e) 246 | { 247 | DrawForm draw= new DrawForm(); 248 | draw.ShowDialog(); 249 | } 250 | } 251 | } 252 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/ImageProcessorForm.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 17, 17 122 | 123 | 124 | 132, 17 125 | 126 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/KernelEditor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Windows.Forms; 5 | 6 | namespace winforms_image_processor 7 | { 8 | public partial class KernelEditor : Form 9 | { 10 | public KernelEditor() 11 | { 12 | InitializeComponent(); 13 | SetUpKernelEditor(); 14 | } 15 | 16 | private ImageProcessorForm imageProcessorForm; 17 | private string kernel; 18 | public KernelEditor(Form callingForm, string filter) 19 | { 20 | imageProcessorForm = callingForm as ImageProcessorForm; 21 | kernel = filter; 22 | InitializeComponent(); 23 | SetUpKernelEditor(); 24 | } 25 | 26 | public static List filterTypes = new List() 27 | { 28 | "", 29 | "Sharpen", 30 | "Gaussian Blur", 31 | "Box Blur", 32 | "Emboss", 33 | "Outline" 34 | }; 35 | 36 | public void SetUpKernelEditor() 37 | { 38 | Console.WriteLine(kernel); 39 | CustomKernel customKernel = Kernel.customKernels[kernel]; 40 | 41 | CBFilterType.DataSource = filterTypes; 42 | 43 | NUDDivisor.Minimum = decimal.MinValue; 44 | NUDDivisor.Maximum = decimal.MaxValue; 45 | 46 | NUDDivisor.Value = customKernel.divisor; 47 | NUDKernelColumn.Value = customKernel.kernel.GetLength(0); 48 | NUDKernelRow.Value = customKernel.kernel.GetLength(1); 49 | 50 | NUDOffset.Value = customKernel.offset; 51 | NUDAnchorCol.Value = customKernel.anchor.X; 52 | NUDAnchorRow.Value = customKernel.anchor.Y; 53 | 54 | SetUpTableLayout(customKernel.kernel.GetLength(0), customKernel.kernel.GetLength(1), customKernel.kernel); 55 | } 56 | 57 | public void SetUpTableLayout(int columns, int rows, double[,] kernel) 58 | { 59 | for (int row = 0; row < tableLayoutPanel1.RowCount; row++) 60 | for (int column = 0; column < tableLayoutPanel1.ColumnCount; column++) 61 | if (tableLayoutPanel1.GetControlFromPosition(column, row) != null) 62 | tableLayoutPanel1.GetControlFromPosition(column, row).Dispose(); 63 | 64 | tableLayoutPanel1.ColumnCount = columns; 65 | tableLayoutPanel1.RowCount = rows; 66 | 67 | for (int row = 0; row < tableLayoutPanel1.RowCount; row++) 68 | { 69 | for (int column = 0; column < tableLayoutPanel1.ColumnCount; column++) 70 | { 71 | NumericUpDown numericUpDown = new NumericUpDown(); 72 | tableLayoutPanel1.Controls.Add(numericUpDown, column, row); 73 | numericUpDown.Minimum = decimal.MinValue; 74 | numericUpDown.Maximum = decimal.MaxValue; 75 | numericUpDown.Value = (decimal)kernel[column, row]; 76 | numericUpDown.Dock = DockStyle.Fill; 77 | } 78 | } 79 | } 80 | 81 | public void SetUpTableLayout(int columns, int rows) 82 | { 83 | for (int row = 0; row < tableLayoutPanel1.RowCount; row++) 84 | for (int column = 0; column < tableLayoutPanel1.ColumnCount; column++) 85 | tableLayoutPanel1.GetControlFromPosition(column, row).Dispose(); 86 | 87 | tableLayoutPanel1.ColumnCount = columns; 88 | tableLayoutPanel1.RowCount = rows; 89 | 90 | for (int row = 0; row < tableLayoutPanel1.RowCount; row++) 91 | { 92 | for (int column = 0; column < tableLayoutPanel1.ColumnCount; column++) 93 | { 94 | NumericUpDown numericUpDown = new NumericUpDown(); 95 | tableLayoutPanel1.Controls.Add(numericUpDown, column, row); 96 | numericUpDown.Value = 0; 97 | numericUpDown.Dock = DockStyle.Fill; 98 | numericUpDown.Minimum = decimal.MinValue; 99 | numericUpDown.Maximum = decimal.MaxValue; 100 | } 101 | } 102 | } 103 | public void SetKernelFromEditor() 104 | { 105 | double[,] kernel = new double[tableLayoutPanel1.ColumnCount, tableLayoutPanel1.RowCount]; 106 | for (int row = 0; row < tableLayoutPanel1.RowCount; row++) 107 | { 108 | for (int column = 0; column < tableLayoutPanel1.ColumnCount; column++) 109 | { 110 | NumericUpDown numUpDown = (NumericUpDown)tableLayoutPanel1.GetControlFromPosition(column, row); 111 | kernel[column, row] = (double)numUpDown.Value; 112 | } 113 | } 114 | 115 | int value = (int)NUDDivisor.Value; 116 | 117 | if (value == 0) 118 | { 119 | foreach (double i in kernel) 120 | value += (int)i; 121 | } 122 | if (value == 0) 123 | value = 1; 124 | 125 | Kernel.customKernels[this.kernel] = new CustomKernel( 126 | kernel, 127 | value, 128 | (int)NUDOffset.Value, 129 | new Point((int)NUDAnchorCol.Value, (int)NUDAnchorRow.Value) 130 | ); 131 | } 132 | 133 | private void button2_Click(object sender, EventArgs e) 134 | { 135 | DialogResult = DialogResult.Cancel; 136 | Close(); 137 | } 138 | 139 | private void label3_MouseHover(object sender, EventArgs e) 140 | { 141 | ToolTip ToolTip1 = new ToolTip(); 142 | ToolTip1.SetToolTip(label3, "Leave 0 for automatic calculation."); 143 | } 144 | 145 | private void RowCol_OnValueChanged(object sender, EventArgs e) 146 | { 147 | NumericUpDown numUpDown = (NumericUpDown)sender; 148 | if (numUpDown.Value % 2 == 0) 149 | { 150 | numUpDown.Value = numUpDown.Value - 1; 151 | } 152 | } 153 | 154 | private void button1_Click(object sender, EventArgs e) 155 | { 156 | SetKernelFromEditor(); 157 | 158 | DialogResult = DialogResult.OK; 159 | 160 | Close(); 161 | } 162 | 163 | private void Redraw_Click(object sender, EventArgs e) 164 | { 165 | switch ((string)CBFilterType.SelectedItem) 166 | { 167 | case "": 168 | SetUpTableLayout((int)NUDKernelColumn.Value, (int)NUDKernelRow.Value); 169 | break; 170 | case "Sharpen": 171 | SetUpTableLayout(3, 3, Kernel.SharpenKernel.kernel); 172 | NUDDivisor.Value = Kernel.SharpenKernel.divisor; 173 | break; 174 | case "Gaussian Blur": 175 | SetUpTableLayout(3, 3, Kernel.GaussianBlurKernel.kernel); 176 | NUDDivisor.Value = Kernel.GaussianBlurKernel.divisor; 177 | break; 178 | case "Box Blur": 179 | SetUpTableLayout(3, 3, Kernel.BoxBlurKernel.kernel); 180 | NUDDivisor.Value = Kernel.BoxBlurKernel.divisor; 181 | break; 182 | case "Emboss": 183 | SetUpTableLayout(3, 3, Kernel.EmbossKernel.kernel); 184 | NUDDivisor.Value = Kernel.EmbossKernel.divisor; 185 | break; 186 | case "Outline": 187 | SetUpTableLayout(3, 3, Kernel.OutlineKernel.kernel); 188 | NUDDivisor.Value = Kernel.OutlineKernel.divisor; 189 | break; 190 | } 191 | 192 | CBFilterType.SelectedIndex = 0; 193 | } 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/KernelEditor.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using System.Windows.Forms; 6 | 7 | namespace winforms_image_processor 8 | { 9 | static class Program 10 | { 11 | /// 12 | /// The main entry point for the application. 13 | /// 14 | [STAThread] 15 | static void Main() 16 | { 17 | Application.EnableVisualStyles(); 18 | Application.SetCompatibleTextRenderingDefault(false); 19 | Application.Run(new ImageProcessorForm()); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/YBRColorspaceDisplay.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace winforms_image_processor 2 | { 3 | partial class YBRColorspaceDisplay 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); 32 | this.YImage = new System.Windows.Forms.PictureBox(); 33 | this.CbImage = new System.Windows.Forms.PictureBox(); 34 | this.CrImage = new System.Windows.Forms.PictureBox(); 35 | this.tableLayoutPanel1.SuspendLayout(); 36 | ((System.ComponentModel.ISupportInitialize)(this.YImage)).BeginInit(); 37 | ((System.ComponentModel.ISupportInitialize)(this.CbImage)).BeginInit(); 38 | ((System.ComponentModel.ISupportInitialize)(this.CrImage)).BeginInit(); 39 | this.SuspendLayout(); 40 | // 41 | // tableLayoutPanel1 42 | // 43 | this.tableLayoutPanel1.ColumnCount = 1; 44 | this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); 45 | this.tableLayoutPanel1.Controls.Add(this.YImage, 0, 0); 46 | this.tableLayoutPanel1.Controls.Add(this.CbImage, 0, 1); 47 | this.tableLayoutPanel1.Controls.Add(this.CrImage, 0, 2); 48 | this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; 49 | this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); 50 | this.tableLayoutPanel1.Name = "tableLayoutPanel1"; 51 | this.tableLayoutPanel1.RowCount = 3; 52 | this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); 53 | this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); 54 | this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); 55 | this.tableLayoutPanel1.Size = new System.Drawing.Size(284, 450); 56 | this.tableLayoutPanel1.TabIndex = 0; 57 | // 58 | // YImage 59 | // 60 | this.YImage.Dock = System.Windows.Forms.DockStyle.Fill; 61 | this.YImage.Location = new System.Drawing.Point(3, 3); 62 | this.YImage.Name = "YImage"; 63 | this.YImage.Size = new System.Drawing.Size(278, 143); 64 | this.YImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; 65 | this.YImage.TabIndex = 0; 66 | this.YImage.TabStop = false; 67 | // 68 | // CbImage 69 | // 70 | this.CbImage.Dock = System.Windows.Forms.DockStyle.Fill; 71 | this.CbImage.Location = new System.Drawing.Point(3, 152); 72 | this.CbImage.Name = "CbImage"; 73 | this.CbImage.Size = new System.Drawing.Size(278, 143); 74 | this.CbImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; 75 | this.CbImage.TabIndex = 1; 76 | this.CbImage.TabStop = false; 77 | // 78 | // CrImage 79 | // 80 | this.CrImage.Dock = System.Windows.Forms.DockStyle.Fill; 81 | this.CrImage.Location = new System.Drawing.Point(3, 301); 82 | this.CrImage.Name = "CrImage"; 83 | this.CrImage.Size = new System.Drawing.Size(278, 146); 84 | this.CrImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; 85 | this.CrImage.TabIndex = 2; 86 | this.CrImage.TabStop = false; 87 | // 88 | // YBRColorspaceDisplay 89 | // 90 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 91 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 92 | this.ClientSize = new System.Drawing.Size(284, 450); 93 | this.Controls.Add(this.tableLayoutPanel1); 94 | this.Name = "YBRColorspaceDisplay"; 95 | this.Text = "YBRColorspaceDisplay"; 96 | this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.YBRColorspaceDisplay_FormClosed); 97 | this.tableLayoutPanel1.ResumeLayout(false); 98 | ((System.ComponentModel.ISupportInitialize)(this.YImage)).EndInit(); 99 | ((System.ComponentModel.ISupportInitialize)(this.CbImage)).EndInit(); 100 | ((System.ComponentModel.ISupportInitialize)(this.CrImage)).EndInit(); 101 | this.ResumeLayout(false); 102 | 103 | } 104 | 105 | #endregion 106 | 107 | private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; 108 | private System.Windows.Forms.PictureBox YImage; 109 | private System.Windows.Forms.PictureBox CbImage; 110 | private System.Windows.Forms.PictureBox CrImage; 111 | } 112 | } -------------------------------------------------------------------------------- /winforms-image-processor/Forms/YBRColorspaceDisplay.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Windows.Forms; 10 | 11 | namespace winforms_image_processor 12 | { 13 | public partial class YBRColorspaceDisplay : Form 14 | { 15 | private ImageProcessorForm imageProcessorForm; 16 | private Bitmap currentFilterImage; 17 | 18 | public YBRColorspaceDisplay(Form callerForm, Bitmap currentFltImage) 19 | { 20 | currentFilterImage = CacheManager.DeepCopy(currentFltImage); 21 | imageProcessorForm = callerForm as ImageProcessorForm; 22 | 23 | InitializeComponent(); 24 | 25 | Height = callerForm.Height; 26 | 27 | setUpImages(); 28 | } 29 | 30 | public void setUpImages() 31 | { 32 | setUpYImage(); 33 | setUpCbImage(); 34 | setUpCrImage(); 35 | } 36 | 37 | public void updateImages(Bitmap currFltImage) 38 | { 39 | currentFilterImage = currFltImage; 40 | 41 | setUpImages(); 42 | } 43 | 44 | void setUpYImage() 45 | { 46 | Bitmap YImageBmp = CacheManager.DeepCopy(currentFilterImage); 47 | 48 | YImageBmp = YImageBmp.ApplyFilter(FilterManager.YGrayscale); 49 | 50 | YImage.Image = YImageBmp; 51 | } 52 | 53 | void setUpCbImage() 54 | { 55 | Bitmap CbImageBmp = CacheManager.DeepCopy(currentFilterImage); 56 | 57 | CbImageBmp = CbImageBmp.ApplyFilter(FilterManager.CbInterpolate); 58 | 59 | CbImage.Image = CbImageBmp; 60 | } 61 | 62 | void setUpCrImage() 63 | { 64 | Bitmap CrImageBmp = CacheManager.DeepCopy(currentFilterImage); 65 | 66 | CrImageBmp = CrImageBmp.ApplyFilter(FilterManager.CrInterpolate); 67 | 68 | CrImage.Image = CrImageBmp; 69 | } 70 | 71 | private void YBRColorspaceDisplay_FormClosed(object sender, FormClosedEventArgs e) 72 | { 73 | imageProcessorForm.yBRColorspaceDisplay = null; 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /winforms-image-processor/Forms/YBRColorspaceDisplay.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /winforms-image-processor/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("winforms-image-processor")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("winforms-image-processor")] 13 | [assembly: AssemblyCopyright("Copyright © 2020")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("11f06003-a488-40ff-bf13-ff7114f9d866")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /winforms-image-processor/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace winforms_image_processor.Properties { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resources() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("winforms_image_processor.Properties.Resources", typeof(Resources).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /winforms-image-processor/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | text/microsoft-resx 107 | 108 | 109 | 2.0 110 | 111 | 112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 113 | 114 | 115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | -------------------------------------------------------------------------------- /winforms-image-processor/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace winforms_image_processor.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 19 | 20 | public static Settings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /winforms-image-processor/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /winforms-image-processor/SaveTools/ShapeSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Runtime.Serialization.Formatters.Binary; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace winforms_image_processor 12 | { 13 | public static class ShapeSerializer 14 | { 15 | public static BindingList Load(string filename) where T : class 16 | { 17 | if (File.Exists(filename)) 18 | { 19 | BindingList bList = new BindingList(); 20 | 21 | using (Stream stream = File.OpenRead(filename)) 22 | { 23 | BinaryFormatter formatter = new BinaryFormatter(); 24 | 25 | while (stream.Position != stream.Length) 26 | { 27 | object result = formatter.Deserialize(stream); 28 | bList.Add((T)result); 29 | } 30 | 31 | return bList; 32 | } 33 | } 34 | return new BindingList(); 35 | } 36 | 37 | public static void Save(string filename, BindingList data) where T : class 38 | { 39 | using (Stream stream = File.OpenWrite(filename)) 40 | { 41 | BinaryFormatter formatter = new BinaryFormatter(); 42 | 43 | foreach (var shape in data) 44 | { 45 | var shaped = shape as Shape; 46 | switch (shaped.shapeType) 47 | { 48 | case DrawingShape.CIRCLE: 49 | formatter.Serialize(stream, (MidPointCircle)shaped); 50 | break; 51 | case DrawingShape.LINE: 52 | formatter.Serialize(stream, (MidPointLine)shaped); 53 | break; 54 | case DrawingShape.POLY: 55 | formatter.Serialize(stream, (Polygon)shaped); 56 | break; 57 | case DrawingShape.CPOLY: 58 | formatter.Serialize(stream, (ClippedPolygon)shaped); 59 | break; 60 | case DrawingShape.CAPS: 61 | formatter.Serialize(stream, (Capsule)shaped); 62 | break; 63 | case DrawingShape.RECT: 64 | formatter.Serialize(stream, (Rectangle)shaped); 65 | break; 66 | case DrawingShape.FILL: 67 | formatter.Serialize(stream, (Fill)shaped); 68 | break; 69 | } 70 | } 71 | } 72 | } 73 | 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /winforms-image-processor/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /winforms-image-processor/winforms-image-processor.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {11F06003-A488-40FF-BF13-FF7114F9D866} 8 | WinExe 9 | winforms_image_processor 10 | winforms-image-processor 11 | v4.7.2 12 | 512 13 | true 14 | true 15 | 16 | 17 | 18 | AnyCPU 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | true 27 | 28 | 29 | AnyCPU 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | Form 72 | 73 | 74 | ConstantsEditor.cs 75 | 76 | 77 | Form 78 | 79 | 80 | DrawForm.cs 81 | 82 | 83 | Form 84 | 85 | 86 | FillMenu.cs 87 | 88 | 89 | Form 90 | 91 | 92 | ImageProcessorForm.cs 93 | 94 | 95 | Form 96 | 97 | 98 | KernelEditor.cs 99 | 100 | 101 | 102 | Form 103 | 104 | 105 | YBRColorspaceDisplay.cs 106 | 107 | 108 | 109 | 110 | ConstantsEditor.cs 111 | 112 | 113 | DrawForm.cs 114 | 115 | 116 | FillMenu.cs 117 | 118 | 119 | ImageProcessorForm.cs 120 | 121 | 122 | KernelEditor.cs 123 | 124 | 125 | YBRColorspaceDisplay.cs 126 | 127 | 128 | ResXFileCodeGenerator 129 | Resources.Designer.cs 130 | Designer 131 | 132 | 133 | True 134 | Resources.resx 135 | True 136 | 137 | 138 | 139 | SettingsSingleFileGenerator 140 | Settings.Designer.cs 141 | 142 | 143 | True 144 | Settings.settings 145 | True 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | --------------------------------------------------------------------------------