From 99a2be9311c01c4a3bc155c65d7cf5400575d380 Mon Sep 17 00:00:00 2001 From: Wayfarer Date: Fri, 3 Jan 2025 20:50:08 +0100 Subject: [PATCH] sync back some usefull stuff --- CommonControls/AssemblyInfo.cs | 2 +- CommonControls/ColorPicker.xaml.cs | 49 ++---- CommonControls/ColorPickerHelper.cs | 2 +- CommonControls/ColorPickerRegister.cs | 2 +- CommonControls/ColorProcessing.cs | 35 ++-- CommonControls/ColorSelection.xaml.cs | 12 +- CommonControls/Colorpick.cs | 70 +++----- CommonControls/ColorpickerMenu.xaml.cs | 2 +- CommonControls/ComCtlResources.cs | 2 +- CommonControls/CommonControlsException.cs | 2 +- CommonControls/DataItem.cs | 2 +- CommonControls/DataList.xaml.cs | 2 +- CommonControls/DataListView.cs | 47 ++---- CommonControls/ExtendedGrid.cs | 12 +- CommonControls/GlobalKeyHandler.cs | 28 +--- CommonControls/ImageEventArgs.cs | 2 +- CommonControls/ImageZoom.xaml.cs | 45 +----- CommonControls/ImageZoomTools.cs | 2 +- CommonControls/ScrollingTextBoxes.cs | 12 +- CommonControls/SelectionAdorner.cs | 6 +- CommonControls/SelectionFrame.cs | 2 +- CommonControls/Thumbnails.xaml.cs | 160 ++++--------------- CommonLibraryTests/DirectBitmapImageTests.cs | 2 +- CommonLibraryTests/RenderingTests.cs | 30 ++-- ImageCompare/AnalysisProcessing.cs | 34 +--- ImageCompare/IImageAnalysis.cs | 2 +- ImageCompare/IImageCompare.cs | 2 +- ImageCompare/ImageAnalysis.cs | 27 +--- ImageCompare/ImageColor.cs | 32 +--- ImageCompare/ImageColoring.cs | 14 +- ImageCompare/ImageCompare.cs | 2 +- ImageCompare/ImageCompareData.cs | 2 +- ImageCompare/ImageData.cs | 2 +- ImageCompare/ImageDuplicate.cs | 22 +-- ImageCompare/ImageDuplication.cs | 14 +- ImageCompare/ImageHelper.cs | 6 +- ImageCompare/ImageProcessing.cs | 29 ++-- ImageCompare/ImageResources.cs | 2 +- ImageCompare/ImageSimilar.cs | 28 +--- ImageCompare/ImageSimilarity.cs | 24 +-- ImageCompare/ImageSlider.cs | 24 +-- Imaging/Cif.cs | 73 ++------- Imaging/CifImageData.cs | 23 +-- Imaging/CifMetadata.cs | 4 +- Imaging/CifProcessing.cs | 39 +---- Imaging/ColorHsv.cs | 89 +++-------- Imaging/CustomImageFormat.cs | 2 +- Imaging/DirectBitmap.cs | 106 +++++------- Imaging/DirectBitmapImage.cs | 29 +--- Imaging/FiltersAreas.cs | 33 ++-- Imaging/FiltersConfig.cs | 2 +- Imaging/FiltersStream.cs | 33 ++-- Imaging/FiltersType.cs | 2 +- Imaging/ICustomImageFormat.cs | 2 +- Imaging/IImageRender.cs | 26 ++- Imaging/ITextureGenerator.cs | 26 ++- Imaging/ImageConverter.cs | 2 +- Imaging/ImageExtension.cs | 2 +- Imaging/ImageGif.cs | 30 +--- Imaging/ImageGifHandler.cs | 19 +-- Imaging/ImageGifInfo.cs | 2 +- Imaging/ImageGifMetadataExtractor.cs | 29 ++-- Imaging/ImageHelper.cs | 67 ++------ Imaging/ImageMask.cs | 2 +- Imaging/ImageOverlays.cs | 16 +- Imaging/ImageRegister.cs | 37 +++-- Imaging/ImageRender.cs | 24 ++- Imaging/ImageStream.cs | 82 +++------- Imaging/ImageStreamHsv.cs | 7 +- Imaging/ImageStreamMedia.cs | 2 +- Imaging/ImagingResources.cs | 29 ++-- Imaging/LayerSettings.cs | 2 +- Imaging/Lif.cs | 13 +- Imaging/LifProcessing.cs | 26 +-- Imaging/MaskShape.cs | 2 +- Imaging/PixelData.cs | 2 +- Imaging/TextureAreas.cs | 7 +- Imaging/TextureConfiguration.cs | 2 +- Imaging/TextureGenerator.cs | 14 +- Imaging/TextureStream.cs | 56 +++---- Imaging/TextureType.cs | 2 +- Mathematics/ExtendedMath.cs | 28 +++- RenderEngine/ImageProcessor.cs | 2 - RenderEngine/RenderEngine.csproj | 1 + RenderEngine/SkiaPixelControl.cs | 151 +++++++++++++++++ RenderEngine/Tester.cs | 60 ------- 86 files changed, 669 insertions(+), 1334 deletions(-) create mode 100644 RenderEngine/SkiaPixelControl.cs delete mode 100644 RenderEngine/Tester.cs diff --git a/CommonControls/AssemblyInfo.cs b/CommonControls/AssemblyInfo.cs index b9d746b1..4a05c7d4 100644 --- a/CommonControls/AssemblyInfo.cs +++ b/CommonControls/AssemblyInfo.cs @@ -7,4 +7,4 @@ ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) -)] +)] \ No newline at end of file diff --git a/CommonControls/ColorPicker.xaml.cs b/CommonControls/ColorPicker.xaml.cs index 367b45f1..8e6b8396 100644 --- a/CommonControls/ColorPicker.xaml.cs +++ b/CommonControls/ColorPicker.xaml.cs @@ -176,10 +176,7 @@ public double Hue get => _hue; set { - if (_hue.IsEqualTo(value, 10) || value * 180 / Math.PI is > 360 or < 0) - { - return; - } + if (_hue.IsEqualTo(value, 10) || value * 180 / Math.PI is > 360 or < 0) return; ColorPickerRegister.ColorChanged = true; @@ -200,10 +197,7 @@ public double Sat get => _sat; set { - if (_sat.IsEqualTo(value, 10) || value is > 1 or < 0) - { - return; - } + if (_sat.IsEqualTo(value, 10) || value is > 1 or < 0) return; ColorPickerRegister.ColorChanged = true; @@ -224,10 +218,7 @@ public double Val get => _val; set { - if (_val.IsEqualTo(value, 10) || value is > 1 or < 0) - { - return; - } + if (_val.IsEqualTo(value, 10) || value is > 1 or < 0) return; ColorPickerRegister.ColorChanged = true; @@ -248,10 +239,7 @@ public int R get => _r; set { - if (_r == value || value is > 255 or < 0) - { - return; - } + if (_r == value || value is > 255 or < 0) return; ColorPickerRegister.ColorChanged = true; @@ -272,10 +260,7 @@ public int G get => _g; set { - if (_g == value || value is > 255 or < 0) - { - return; - } + if (_g == value || value is > 255 or < 0) return; ColorPickerRegister.ColorChanged = true; @@ -296,10 +281,7 @@ public int B get => _b; set { - if (_b == value || value is > 255 or < 0) - { - return; - } + if (_b == value || value is > 255 or < 0) return; ColorPickerRegister.ColorChanged = true; @@ -319,10 +301,7 @@ public int Alpha get => _alpha; set { - if (_alpha == value || value is > 255 or < 0) - { - return; - } + if (_alpha == value || value is > 255 or < 0) return; ColorPickerRegister.ColorChanged = true; @@ -350,10 +329,7 @@ public string Hex get => _hex; set { - if (_hex == value) - { - return; - } + if (_hex == value) return; ColorPickerRegister.ColorChanged = true; @@ -413,9 +389,7 @@ private static void OnShowTextBoxesChanged(DependencyObject d, DependencyPropert { if (d is ColorPicker colorPicker) // Force layout update on visibility change - { colorPicker.UpdateLayout(); - } } /// @@ -497,10 +471,7 @@ private void SetPreview() _ = CanvasPreview.Children.Add(rectangle); - if (ColorPickerRegister.ColorChanged) - { - OnColorChanged(); - } + if (ColorPickerRegister.ColorChanged) OnColorChanged(); } /// @@ -511,4 +482,4 @@ private void OnColorChanged() ColorChanged?.Invoke(ColorPickerRegister.Colors); } } -} +} \ No newline at end of file diff --git a/CommonControls/ColorPickerHelper.cs b/CommonControls/ColorPickerHelper.cs index 4e3cd4bb..bb83ab61 100644 --- a/CommonControls/ColorPickerHelper.cs +++ b/CommonControls/ColorPickerHelper.cs @@ -35,4 +35,4 @@ internal static Rectangle GetColorPreview(ColorHsv colorHsv) return rectangle; } } -} +} \ No newline at end of file diff --git a/CommonControls/ColorPickerRegister.cs b/CommonControls/ColorPickerRegister.cs index 48cc0cdb..63600391 100644 --- a/CommonControls/ColorPickerRegister.cs +++ b/CommonControls/ColorPickerRegister.cs @@ -41,4 +41,4 @@ internal static class ColorPickerRegister /// internal static ColorHsv Colors { get; set; } } -} +} \ No newline at end of file diff --git a/CommonControls/ColorProcessing.cs b/CommonControls/ColorProcessing.cs index da65e679..b5c209bb 100644 --- a/CommonControls/ColorProcessing.cs +++ b/CommonControls/ColorProcessing.cs @@ -49,7 +49,7 @@ internal static bool InCircle(double x, double y) var xDelta = x - Center; var yDelta = y - Center; - var dist = (int)Math.Sqrt((xDelta * xDelta) + (yDelta * yDelta)); + var dist = (int)Math.Sqrt(xDelta * xDelta + yDelta * yDelta); return (ColorPickerRegister.InternSize / 2).Interval(dist, 20); } @@ -62,12 +62,9 @@ internal static bool InCircle(double x, double y) /// New Hue Value internal static double CalcHue(double x, double y) { - var angle = Math.Atan2(y - Center, x - Center) + (Math.PI / 2); + var angle = Math.Atan2(y - Center, x - Center) + Math.PI / 2; - if (angle < 0) - { - angle += 2 * Math.PI; - } + if (angle < 0) angle += 2 * Math.PI; return angle; } @@ -90,29 +87,17 @@ internal static bool InTriangle(double x, double y) //measures: max y = 190, max x = 189 //upper and lower limit - if (y is < 16 or >= 135) - { - return false; - } + if (y is < 16 or >= 135) return false; // Inside var sqrt3 = Math.Sqrt(3); var x1 = (x - Center) * 1.0 / InnerRadius; var y1 = (y - Center) * 1.0 / InnerRadius; - if ((0 * x1) + (2 * y1) > 1) - { - return false; - } + if (0 * x1 + 2 * y1 > 1) return false; - if ((sqrt3 * x1) + (-1 * y1) > 1) - { - return false; - } + if (sqrt3 * x1 + -1 * y1 > 1) return false; - if ((-sqrt3 * x1) + (-1 * y1) > 1) - { - return false; - } + if (-sqrt3 * x1 + -1 * y1 > 1) return false; return true; } @@ -128,7 +113,7 @@ internal static double CalcVal(double x, double y) var x1 = (x - Center) * 1.0 / InnerRadius; var y1 = (y - Center) * 1.0 / InnerRadius; - return ((Sqrt3 * x1) - y1 + 2) / 3; + return (Sqrt3 * x1 - y1 + 2) / 3; } /// @@ -142,7 +127,7 @@ internal static double CalcSat(double x, double y) var x1 = (x - Center) * 1.0 / InnerRadius; var y1 = (y - Center) * 1.0 / InnerRadius; - return (1 - (2 * y1)) / ((Sqrt3 * x1) - y1 + 2); + return (1 - 2 * y1) / (Sqrt3 * x1 - y1 + 2); } } -} +} \ No newline at end of file diff --git a/CommonControls/ColorSelection.xaml.cs b/CommonControls/ColorSelection.xaml.cs index e56d42bb..5e36052c 100644 --- a/CommonControls/ColorSelection.xaml.cs +++ b/CommonControls/ColorSelection.xaml.cs @@ -128,10 +128,7 @@ private void CmbColor_SelectionChanged(object sender, SelectionChangedEventArgs { try { - if (CmbColor?.SelectedItem is not PropertyInfo property) - { - return; - } + if (CmbColor?.SelectedItem is not PropertyInfo property) return; var selectedColor = (Color)property.GetValue(null, null); StartColor = _colorDct.FirstOrDefault(x => x.Value == selectedColor).Key; @@ -184,10 +181,7 @@ private static Dictionary InitiateColors() /// private void SwitchToStartColor() { - if (string.IsNullOrEmpty(StartColor)) - { - return; - } + if (string.IsNullOrEmpty(StartColor)) return; CmbColor.SelectedItem = typeof(Colors).GetProperty(StartColor); } @@ -202,4 +196,4 @@ private static void ShowErrorMessageBox(string message, Exception ex) MessageBox.Show($"{message}: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } -} +} \ No newline at end of file diff --git a/CommonControls/Colorpick.cs b/CommonControls/Colorpick.cs index 69174d6d..62c8b724 100644 --- a/CommonControls/Colorpick.cs +++ b/CommonControls/Colorpick.cs @@ -135,10 +135,7 @@ internal static void Selection(double x, double y, int alpha) //Check circle check = ColorProcessing.InCircle(x, y); - if (check) - { - _hue = ColorProcessing.CalcHue(x, y); - } + if (check) _hue = ColorProcessing.CalcHue(x, y); ColorPickerRegister.Colors = new ColorHsv(_hue, _sat, _val, alpha); } @@ -189,23 +186,18 @@ private static Image DrawImage(double hue = 3.3, double sat = 1.0, double val = /// Clicked results private static PickResult Pick(double x, double y) { - var distanceFromCenter = Math.Sqrt(((x - Center) * (x - Center)) + ((y - Center) * (y - Center))); + var distanceFromCenter = Math.Sqrt((x - Center) * (x - Center) + (y - Center) * (y - Center)); var sqrt3 = Math.Sqrt(3); if (distanceFromCenter > OuterRadius) // Outside - { return new PickResult { Area = Area.Outside }; - } if (distanceFromCenter > InnerRadius) { // Wheel - var angle = Math.Atan2(y - Center, x - Center) + (Math.PI / 2); - if (angle < 0) - { - angle += 2 * Math.PI; - } + var angle = Math.Atan2(y - Center, x - Center) + Math.PI / 2; + if (angle < 0) angle += 2 * Math.PI; var hue = angle; @@ -215,24 +207,15 @@ private static PickResult Pick(double x, double y) // Inside var x1 = (x - Center) * 1.0 / InnerRadius; var y1 = (y - Center) * 1.0 / InnerRadius; - if ((0 * x1) + (2 * y1) > 1) - { - return new PickResult { Area = Area.Outside }; - } + if (0 * x1 + 2 * y1 > 1) return new PickResult { Area = Area.Outside }; - if ((sqrt3 * x1) + (-1 * y1) > 1) - { - return new PickResult { Area = Area.Outside }; - } + if (sqrt3 * x1 + -1 * y1 > 1) return new PickResult { Area = Area.Outside }; - if ((-sqrt3 * x1) + (-1 * y1) > 1) - { - return new PickResult { Area = Area.Outside }; - } + if (-sqrt3 * x1 + -1 * y1 > 1) return new PickResult { Area = Area.Outside }; // Triangle - var sat = (1 - (2 * y1)) / ((sqrt3 * x1) - y1 + 2); - var val = ((sqrt3 * x1) - y1 + 2) / 3; + var sat = (1 - 2 * y1) / (sqrt3 * x1 - y1 + 2); + var val = (sqrt3 * x1 - y1 + 2) / 3; return new PickResult { Area = Area.Triangle, Sat = sat, Val = val }; } @@ -249,33 +232,18 @@ private static Color Hsv(double hue, double sat, double val, double alpha) { var chroma = val * sat; const double step = Math.PI / 3; - var intern = chroma * (1 - Math.Abs((hue / step % 2.0) - 1)); + var intern = chroma * (1 - Math.Abs(hue / step % 2.0 - 1)); var shift = val - chroma; - if (hue < 1 * step) - { - return Rgb(shift + chroma, shift + intern, shift + 0, alpha); - } + if (hue < 1 * step) return Rgb(shift + chroma, shift + intern, shift + 0, alpha); - if (hue < 2 * step) - { - return Rgb(shift + intern, shift + chroma, shift + 0, alpha); - } + if (hue < 2 * step) return Rgb(shift + intern, shift + chroma, shift + 0, alpha); - if (hue < 3 * step) - { - return Rgb(shift + 0, shift + chroma, shift + intern, alpha); - } + if (hue < 3 * step) return Rgb(shift + 0, shift + chroma, shift + intern, alpha); - if (hue < 4 * step) - { - return Rgb(shift + 0, shift + intern, shift + chroma, alpha); - } + if (hue < 4 * step) return Rgb(shift + 0, shift + intern, shift + chroma, alpha); - if (hue < 5 * step) - { - return Rgb(shift + intern, shift + 0, shift + chroma, alpha); - } + if (hue < 5 * step) return Rgb(shift + intern, shift + 0, shift + chroma, alpha); return Rgb(shift + chroma, shift + 0, shift + intern, alpha); } @@ -290,7 +258,7 @@ private static Point GetWheelPosition() return new Point { - X = Center + (middleRadius * Math.Sin(_hue)), Y = Center - (middleRadius * Math.Cos(_hue)) + X = Center + middleRadius * Math.Sin(_hue), Y = Center - middleRadius * Math.Cos(_hue) }; } @@ -304,8 +272,8 @@ private static Point GetTrianglePosition() return new Point { - X = Center + (InnerRadius * ((2 * _val) - (_sat * _val) - 1) * sqrt3 / 2), - Y = Center + (InnerRadius * (1 - (3 * _sat * _val)) / 2) + X = Center + InnerRadius * (2 * _val - _sat * _val - 1) * sqrt3 / 2, + Y = Center + InnerRadius * (1 - 3 * _sat * _val) / 2 }; } @@ -364,4 +332,4 @@ internal struct PickResult /// internal double Val { get; init; } } -} +} \ No newline at end of file diff --git a/CommonControls/ColorpickerMenu.xaml.cs b/CommonControls/ColorpickerMenu.xaml.cs index b351aab9..608d5f21 100644 --- a/CommonControls/ColorpickerMenu.xaml.cs +++ b/CommonControls/ColorpickerMenu.xaml.cs @@ -124,4 +124,4 @@ private void AddColor(ColorHsv colorHsv) _ = CanvasPreview.Children.Add(rectangle); } } -} +} \ No newline at end of file diff --git a/CommonControls/ComCtlResources.cs b/CommonControls/ComCtlResources.cs index 3db98fc4..cd147944 100644 --- a/CommonControls/ComCtlResources.cs +++ b/CommonControls/ComCtlResources.cs @@ -126,4 +126,4 @@ internal static class ComCtlResources /// internal const string Separator = " , "; } -} +} \ No newline at end of file diff --git a/CommonControls/CommonControlsException.cs b/CommonControls/CommonControlsException.cs index 5f048ef3..c0ef5390 100644 --- a/CommonControls/CommonControlsException.cs +++ b/CommonControls/CommonControlsException.cs @@ -60,4 +60,4 @@ public CommonControlsException(string message, Exception innerException) : base( { } } -} +} \ No newline at end of file diff --git a/CommonControls/DataItem.cs b/CommonControls/DataItem.cs index 0d386a4f..df1b30e2 100644 --- a/CommonControls/DataItem.cs +++ b/CommonControls/DataItem.cs @@ -127,4 +127,4 @@ public override string ToString() return $"{_id}{ComCtlResources.Separator}{_name}"; } } -} +} \ No newline at end of file diff --git a/CommonControls/DataList.xaml.cs b/CommonControls/DataList.xaml.cs index b7a34187..e32ffd27 100644 --- a/CommonControls/DataList.xaml.cs +++ b/CommonControls/DataList.xaml.cs @@ -223,4 +223,4 @@ internal void NotUniqueStart(string name) MessageBoxButton.OK); } } -} +} \ No newline at end of file diff --git a/CommonControls/DataListView.cs b/CommonControls/DataListView.cs index 7492d3ea..16e3af2f 100644 --- a/CommonControls/DataListView.cs +++ b/CommonControls/DataListView.cs @@ -93,10 +93,7 @@ public DataListView(IList dataItems, DataList dataList, bool unique, L { Items = new BindingList { new() { Id = 0, Name = ComCtlResources.DataListEntry } }; - foreach (var item in Items) - { - ChangeLog.Add(item.Id, item, true); - } + foreach (var item in Items) ChangeLog.Add(item.Id, item, true); } else { @@ -118,10 +115,7 @@ public DataListView(IList dataItems, DataList dataList, bool unique, L _unique = unique; - foreach (var item in Items) - { - _id.Add(item.Id); - } + foreach (var item in Items) _id.Add(item.Id); Items.ListChanged += ItemsListChanged; listBox.SelectionChanged += ItemSelected; @@ -196,10 +190,7 @@ public object Selection /// public void UpdateSelectedItem() { - if (_dataList.SelectedItem == null) - { - return; - } + if (_dataList.SelectedItem == null) return; var item = _dataList.SelectedItem; @@ -261,20 +252,14 @@ private string CheckName(string name) { while (true) { - if (!CheckItemName(name)) - { - return name; - } + if (!CheckItemName(name)) return name; var count = 0; while (CheckItemName(name)) { var cache = $"{name}({count++})"; - if (CheckItemName(cache)) - { - continue; - } + if (CheckItemName(cache)) continue; name = cache; } @@ -298,10 +283,7 @@ private bool CheckItemName(string name) private void AddItem(string name) { //basic sanity checks - if (string.IsNullOrEmpty(name)) - { - return; - } + if (string.IsNullOrEmpty(name)) return; var idList = Items.Select(element => element.Id).ToList(); @@ -322,10 +304,7 @@ private void AddItem(string name) private void RemoveItem(DataItem item) { var check = Items.Remove(item); - if (!check) - { - return; - } + if (!check) return; _dataList.Removed(item); } @@ -405,22 +384,16 @@ private void ItemSelected(object sender, SelectionChangedEventArgs e) { var lst = _listBox.SelectedItems; - if (lst.Count == 0) - { - return; - } + if (lst.Count == 0) return; var items = new List(lst.Count); items.AddRange(lst.Cast()); - if (items.Count == 0) - { - return; - } + if (items.Count == 0) return; _dataList.SelectedItem = items[0]; _dataList.SelectedItems = items; } } -} +} \ No newline at end of file diff --git a/CommonControls/ExtendedGrid.cs b/CommonControls/ExtendedGrid.cs index 48601a2e..33cdb94f 100644 --- a/CommonControls/ExtendedGrid.cs +++ b/CommonControls/ExtendedGrid.cs @@ -187,10 +187,7 @@ private static int CalculateTotalWidth(IEnumerable columnWidths) var totalWidth = 0; foreach (var width in columnWidths) { - if (width < 0) - { - throw new CommonControlsException(ComCtlResources.GridExceptionColumn); - } + if (width < 0) throw new CommonControlsException(ComCtlResources.GridExceptionColumn); totalWidth += width; } @@ -206,10 +203,7 @@ private static int CalculateTotalHeight(IEnumerable rowHeights) var totalHeight = 0; foreach (var height in rowHeights) { - if (height < 0) - { - throw new CommonControlsException(ComCtlResources.GridExceptionRow); - } + if (height < 0) throw new CommonControlsException(ComCtlResources.GridExceptionRow); totalHeight += height; } @@ -217,4 +211,4 @@ private static int CalculateTotalHeight(IEnumerable rowHeights) return totalHeight; } } -} +} \ No newline at end of file diff --git a/CommonControls/GlobalKeyHandler.cs b/CommonControls/GlobalKeyHandler.cs index 1d051cf4..774a46c0 100644 --- a/CommonControls/GlobalKeyHandler.cs +++ b/CommonControls/GlobalKeyHandler.cs @@ -104,19 +104,12 @@ public static Dictionary GetCommandBindings(UIElement element) /// private static void OnAttachChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { - if (d is not UIElement element) - { - return; - } + if (d is not UIElement element) return; if ((bool)e.NewValue) // If Attach is set to true - { element.PreviewKeyDown += OnPreviewKeyDown; // Attach the key-down handler - } else // If Attach is set to false - { element.PreviewKeyDown -= OnPreviewKeyDown; // Detach the key-down handler - } } /// @@ -125,37 +118,26 @@ private static void OnAttachChanged(DependencyObject d, DependencyPropertyChange /// private static void OnPreviewKeyDown(object sender, KeyEventArgs e) { - if (e.Handled) - { - return; // Do nothing if the event is already handled - } + if (e.Handled) return; // Do nothing if the event is already handled - if (sender is not UIElement element) - { - return; - } + if (sender is not UIElement element) return; // Get the currently focused element using Keyboard.FocusedElement var focusedElement = Keyboard.FocusedElement; // Check if skipping text controls is enabled if (GetSkipTextControls(element) && focusedElement is TextBox or RichTextBox) - { return; - } // Retrieve the dictionary of key-command bindings for this element var bindings = GetCommandBindings(element); // Check if a command is bound to the pressed key and if it can execute - if (bindings == null || !bindings.TryGetValue(e.Key, out var command) || !command.CanExecute(null)) - { - return; - } + if (bindings == null || !bindings.TryGetValue(e.Key, out var command) || !command.CanExecute(null)) return; // Execute the command if found and mark the event as handled command.Execute(null); e.Handled = true; } } -} +} \ No newline at end of file diff --git a/CommonControls/ImageEventArgs.cs b/CommonControls/ImageEventArgs.cs index f0dd2b16..3adbdc20 100644 --- a/CommonControls/ImageEventArgs.cs +++ b/CommonControls/ImageEventArgs.cs @@ -21,4 +21,4 @@ public sealed class ImageEventArgs : EventArgs /// public int Id { get; internal init; } } -} +} \ No newline at end of file diff --git a/CommonControls/ImageZoom.xaml.cs b/CommonControls/ImageZoom.xaml.cs index c993814a..b3b71842 100644 --- a/CommonControls/ImageZoom.xaml.cs +++ b/CommonControls/ImageZoom.xaml.cs @@ -128,10 +128,7 @@ public sealed partial class ImageZoom : IDisposable public ImageZoom() { InitializeComponent(); - if (BtmImage.Source == null) - { - return; - } + if (BtmImage.Source == null) return; MainCanvas.Height = BtmImage.Source.Height; MainCanvas.Width = BtmImage.Source.Width; @@ -286,18 +283,12 @@ private static void OnImageGifSourcePropertyChanged(DependencyObject sender, private static void OnSelectionToolChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = d as ImageZoom; - if (control == null) - { - return; // Ensure that we are working with an ImageZoom instance - } + if (control == null) return; // Ensure that we are working with an ImageZoom instance var newTool = (ImageZoomTools)e.NewValue; // Detach the previous adorner if needed - if (control.SelectionAdorner == null) - { - return; - } + if (control.SelectionAdorner == null) return; control.SelectionAdorner.Tool = newTool; // Update the tool in the adorner control.SelectionAdorner.ClearFreeFormPoints(); // Reset any existing free-form points if applicable @@ -360,10 +351,7 @@ private void OnImageSourceChanged() BtmImage.StopAnimation(); BtmImage.Source = ItemsSource; - if (BtmImage.Source == null) - { - return; - } + if (BtmImage.Source == null) return; //reset Scaling Scale.ScaleX = 1; @@ -521,10 +509,7 @@ private void Canvas_MouseUp(object sender, MouseButtonEventArgs e) /// The instance containing the event data. private void Canvas_MouseMove(object sender, MouseEventArgs e) { - if (!_mouseDown) - { - return; - } + if (!_mouseDown) return; // Get the mouse position relative to the image instead of the canvas var mousePos = e.GetPosition(BtmImage); @@ -618,17 +603,11 @@ private void SetClickedPoint(MouseEventArgs e) /// Whether the method was called by Dispose or the finalizer. private void Dispose(bool disposing) { - if (_disposed) - { - return; // Early exit if already disposed - } + if (_disposed) return; // Early exit if already disposed lock (_lock) // Ensure thread-safety { - if (_disposed) - { - return; // Double-check in case Dispose was called by another thread - } + if (_disposed) return; // Double-check in case Dispose was called by another thread if (disposing) { @@ -636,20 +615,12 @@ private void Dispose(bool disposing) // Unsubscribe event handlers if (SelectedFrame != null) - { foreach (var d in SelectedFrame.GetInvocationList()) - { SelectedFrame -= (DelegateFrame)d; - } - } if (SelectedPoint != null) - { foreach (var d in SelectedPoint.GetInvocationList()) - { SelectedPoint -= (DelegatePoint)d; - } - } // Dispose image resources BtmImage?.StopAnimation(); @@ -683,4 +654,4 @@ private void Dispose(bool disposing) Dispose(false); // Finalizer calls Dispose(false) } } -} +} \ No newline at end of file diff --git a/CommonControls/ImageZoomTools.cs b/CommonControls/ImageZoomTools.cs index 44b66708..1380adad 100644 --- a/CommonControls/ImageZoomTools.cs +++ b/CommonControls/ImageZoomTools.cs @@ -50,4 +50,4 @@ public enum ImageZoomTools /// FreeForm = 5 } -} +} \ No newline at end of file diff --git a/CommonControls/ScrollingTextBoxes.cs b/CommonControls/ScrollingTextBoxes.cs index 5e958527..f8b074c3 100644 --- a/CommonControls/ScrollingTextBoxes.cs +++ b/CommonControls/ScrollingTextBoxes.cs @@ -61,10 +61,7 @@ protected override void OnInitialized(EventArgs e) /// The text changed event arguments. protected override void OnTextChanged(TextChangedEventArgs e) { - if (!AutoScrolling) - { - return; - } + if (!AutoScrolling) return; base.OnTextChanged(e); CaretIndex = Text.Length; @@ -116,13 +113,10 @@ protected override void OnInitialized(EventArgs e) /// The text changed event arguments. protected override void OnTextChanged(TextChangedEventArgs e) { - if (!AutoScrolling) - { - return; - } + if (!AutoScrolling) return; base.OnTextChanged(e); ScrollToEnd(); } } -} +} \ No newline at end of file diff --git a/CommonControls/SelectionAdorner.cs b/CommonControls/SelectionAdorner.cs index 86d9fd40..52a7ba86 100644 --- a/CommonControls/SelectionAdorner.cs +++ b/CommonControls/SelectionAdorner.cs @@ -220,8 +220,8 @@ protected override void OnRender(DrawingContext drawingContext) case ImageZoomTools.Ellipse: // Calculate the center of the rectangle var center = new Point( - selectionRect.Left + (selectionRect.Width / 2), - selectionRect.Top + (selectionRect.Height / 2)); + selectionRect.Left + selectionRect.Width / 2, + selectionRect.Top + selectionRect.Height / 2); // Draw the ellipse with the calculated center and half the width and height as radii drawingContext.DrawEllipse(null, dashedPen, center, selectionRect.Width / 2, @@ -253,4 +253,4 @@ protected override void OnRender(DrawingContext drawingContext) } } } -} +} \ No newline at end of file diff --git a/CommonControls/SelectionFrame.cs b/CommonControls/SelectionFrame.cs index b21660dc..9c6c9a57 100644 --- a/CommonControls/SelectionFrame.cs +++ b/CommonControls/SelectionFrame.cs @@ -53,4 +53,4 @@ public sealed class SelectionFrame /// public string Tool { get; internal init; } } -} +} \ No newline at end of file diff --git a/CommonControls/Thumbnails.xaml.cs b/CommonControls/Thumbnails.xaml.cs index 3d5602b4..26b7de89 100644 --- a/CommonControls/Thumbnails.xaml.cs +++ b/CommonControls/Thumbnails.xaml.cs @@ -341,15 +341,9 @@ public void Dispose() private static void OnItemsSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var control = sender as Thumbnails; - if (e.NewValue == e.OldValue) - { - return; - } + if (e.NewValue == e.OldValue) return; - if (!_refresh) - { - return; - } + if (!_refresh) return; control?.OnItemsSourceChanged(); } @@ -362,17 +356,11 @@ public void RemoveSingleItem(int id) { _refresh = false; - if (!ItemsSource.ContainsKey(id)) - { - return; - } + if (!ItemsSource.ContainsKey(id)) return; var image = ImageDct[string.Concat(ComCtlResources.ImageAdd, id)]; - if (image != null) - { - image.Source = null; - } + if (image != null) image.Source = null; _ = ItemsSource.Remove(id); @@ -415,10 +403,7 @@ private void UserControl_Loaded(object sender, RoutedEventArgs e) /// private async void LoadImages() { - if (ItemsSource?.Any() != true) - { - return; - } + if (ItemsSource?.Any() != true) return; _cancellationTokenSource = new CancellationTokenSource(); var token = _cancellationTokenSource.Token; @@ -435,33 +420,18 @@ private async void LoadImages() Border = new ConcurrentDictionary(); Selection = new List(); - if (SelectBox) - { - ChkBox = new ConcurrentDictionary(); - } + if (SelectBox) ChkBox = new ConcurrentDictionary(); // Handle special cases - if (ThumbCellSize == 0) - { - ThumbCellSize = 100; - } + if (ThumbCellSize == 0) ThumbCellSize = 100; - if (ThumbHeight == 0 && ThumbWidth == 0) - { - ThumbHeight = 1; - } + if (ThumbHeight == 0 && ThumbWidth == 0) ThumbHeight = 1; if (ThumbHeight * ThumbWidth < pics.Count) { - if (ThumbWidth == 1) - { - ThumbHeight = pics.Count; - } + if (ThumbWidth == 1) ThumbHeight = pics.Count; - if (ThumbHeight == 1) - { - ThumbWidth = pics.Count; - } + if (ThumbHeight == 1) ThumbWidth = pics.Count; if (ThumbHeight != 1 && ThumbWidth != 1 && pics.Count > 1) { @@ -478,18 +448,12 @@ private async void LoadImages() var tasks = new List(); foreach (var (key, name) in pics) { - if (token.IsCancellationRequested) - { - return; - } + if (token.IsCancellationRequested) return; tasks.Add(LoadImageAsync(key, name, exGrid)); // Limit the number of concurrent tasks to avoid overloading - if (tasks.Count < 4) - { - continue; - } + if (tasks.Count < 4) continue; await Task.WhenAll(tasks); tasks.Clear(); @@ -515,10 +479,7 @@ private async void LoadImages() private async Task LoadImageAsync(int key, string name, Panel exGrid) { var token = _cancellationTokenSource.Token; - if (token.IsCancellationRequested) - { - return; - } + if (token.IsCancellationRequested) return; BitmapImage myBitmapCell = null; @@ -565,10 +526,7 @@ private async Task LoadImageAsync(int key, string name, Panel exGrid) Trace.WriteLine(ex); } - if (myBitmapCell == null) - { - return; - } + if (myBitmapCell == null) return; // Set the image source on the UI thread Application.Current.Dispatcher.Invoke(() => @@ -579,7 +537,6 @@ private async Task LoadImageAsync(int key, string name, Panel exGrid) if (SelectBox) // Handle checkboxes for selection on the UI thread - { Application.Current.Dispatcher.Invoke(() => { images.MouseRightButtonDown += ImageClick_MouseRightButtonDown; @@ -593,10 +550,7 @@ private async Task LoadImageAsync(int key, string name, Panel exGrid) IsChecked = IsCheckBoxSelected }; - if (IsCheckBoxSelected) - { - Selection.Add(key); - } + if (IsCheckBoxSelected) Selection.Add(key); checkbox.Checked += CheckBox_Checked; checkbox.Unchecked += CheckBox_Unchecked; @@ -607,7 +561,6 @@ private async Task LoadImageAsync(int key, string name, Panel exGrid) Grid.SetColumn(checkbox, key % ThumbWidth); _ = exGrid.Children.Add(checkbox); }); - } } /// @@ -662,15 +615,9 @@ private static async Task GetBitmapImageFileStreamAsync(string file private void ImageClick_MouseDown(object sender, MouseButtonEventArgs e) { // Get the image that was clicked - if (sender is not Image clickedImage) - { - return; - } + if (sender is not Image clickedImage) return; - if (!Keys.ContainsKey(clickedImage.Name)) - { - return; - } + if (!Keys.ContainsKey(clickedImage.Name)) return; var id = Keys[clickedImage.Name]; @@ -680,10 +627,7 @@ private void ImageClick_MouseDown(object sender, MouseButtonEventArgs e) // Get the parent border (since we wrapped the image in a Border) var clickedBorder = clickedImage.Parent as Border; - if (clickedBorder == null) - { - return; - } + if (clickedBorder == null) return; // Update the selected border (reuse the UpdateSelectedBorder method) UpdateSelectedBorder(clickedBorder); @@ -719,10 +663,7 @@ public void Previous() /// The ID of the item to center on. public void CenterOnItem(int id) { - if (MainScrollViewer == null || Border == null) - { - return; - } + if (MainScrollViewer == null || Border == null) return; // Check if the item with the specified ID exists if (Border.TryGetValue(id, out var targetElement) && targetElement != null) @@ -732,10 +673,10 @@ public void CenterOnItem(int id) var itemPosition = itemTransform.Transform(new Point(0, 0)); // Calculate the offsets needed to center the item - var centerOffsetX = itemPosition.X - (MainScrollViewer.ViewportWidth / 2) + - (targetElement.RenderSize.Width / 2); - var centerOffsetY = itemPosition.Y - (MainScrollViewer.ViewportHeight / 2) + - (targetElement.RenderSize.Height / 2); + var centerOffsetX = itemPosition.X - MainScrollViewer.ViewportWidth / 2 + + targetElement.RenderSize.Width / 2; + var centerOffsetY = itemPosition.Y - MainScrollViewer.ViewportHeight / 2 + + targetElement.RenderSize.Height / 2; // Set the ScrollViewer's offset to center the item MainScrollViewer.ScrollToHorizontalOffset(centerOffsetX); @@ -751,15 +692,9 @@ public void CenterOnItem(int id) private void ImageClick_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { //get the button that was clicked - if (sender is not Image clickedButton) - { - return; - } + if (sender is not Image clickedButton) return; - if (!Keys.ContainsKey(clickedButton.Name)) - { - return; - } + if (!Keys.ContainsKey(clickedButton.Name)) return; _selection = Keys[clickedButton.Name]; @@ -794,15 +729,9 @@ private void Deselect_Click(object sender, RoutedEventArgs e) /// The instance containing the event data. private void DeselectAll_Click(object sender, RoutedEventArgs e) { - if (Selection.Count == 0) - { - return; - } + if (Selection.Count == 0) return; - foreach (var check in new List(Selection).Select(id => ChkBox[id])) - { - check.IsChecked = false; - } + foreach (var check in new List(Selection).Select(id => ChkBox[id])) check.IsChecked = false; } /// @@ -813,15 +742,9 @@ private void DeselectAll_Click(object sender, RoutedEventArgs e) private void CheckBox_Checked(object sender, RoutedEventArgs e) { //get the button that was clicked - if (sender is not CheckBox clickedCheckBox) - { - return; - } + if (sender is not CheckBox clickedCheckBox) return; - if (!Keys.ContainsKey(clickedCheckBox.Name)) - { - return; - } + if (!Keys.ContainsKey(clickedCheckBox.Name)) return; var id = Keys[clickedCheckBox.Name]; @@ -836,15 +759,9 @@ private void CheckBox_Checked(object sender, RoutedEventArgs e) private void CheckBox_Unchecked(object sender, RoutedEventArgs e) { //get the button that was clicked - if (sender is not CheckBox clickedCheckBox) - { - return; - } + if (sender is not CheckBox clickedCheckBox) return; - if (!Keys.ContainsKey(clickedCheckBox.Name)) - { - return; - } + if (!Keys.ContainsKey(clickedCheckBox.Name)) return; var id = Keys[clickedCheckBox.Name]; @@ -883,10 +800,7 @@ private int GetCurrentIndex(string name) /// The index. private void SelectImageAtIndex(int index) { - if (index < 0 || index >= Border.Count || !Border.ContainsKey(index)) - { - return; - } + if (index < 0 || index >= Border.Count || !Border.ContainsKey(index)) return; var border = Border[index]; @@ -921,19 +835,13 @@ private void UpdateSelectedBorder(Border newSelectedBorder) /// if set to true [disposing]. private void Dispose(bool disposing) { - if (_disposed) - { - return; - } + if (_disposed) return; if (disposing) { // Dispose managed resources // e.g., unsubscribe from events, dispose of Image objects, etc. - foreach (var image in Thb.Children.OfType()) - { - image.Source = null; // Release image source - } + foreach (var image in Thb.Children.OfType()) image.Source = null; // Release image source Thb.Children.Clear(); // Clear children from the UI element } diff --git a/CommonLibraryTests/DirectBitmapImageTests.cs b/CommonLibraryTests/DirectBitmapImageTests.cs index 9b87d2da..a19dfb9f 100644 --- a/CommonLibraryTests/DirectBitmapImageTests.cs +++ b/CommonLibraryTests/DirectBitmapImageTests.cs @@ -17,7 +17,7 @@ namespace CommonLibraryTests { /// - /// DirectBitmapImage test cases + /// DirectBitmapImage test cases /// [TestClass] public class DirectBitmapImageTests diff --git a/CommonLibraryTests/RenderingTests.cs b/CommonLibraryTests/RenderingTests.cs index 6e286efe..c7dc3699 100644 --- a/CommonLibraryTests/RenderingTests.cs +++ b/CommonLibraryTests/RenderingTests.cs @@ -1,9 +1,9 @@ -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; using System.Diagnostics; using System.Drawing; using System.IO; using Imaging; -using Microsoft.VisualStudio.TestTools.UnitTesting; using RenderEngine; namespace CommonLibraryTests @@ -51,7 +51,7 @@ public void Cleanup() } /// - /// Test to compare the processing speed between DirectBitmap and SkiaSharp. + /// Test to compare the processing speed between DirectBitmap and SkiaSharp. /// [TestMethod] public void CompareImageProcessingSpeed() @@ -59,40 +59,30 @@ public void CompareImageProcessingSpeed() var imagePath = Path.Combine(SampleImagesFolder.FullName, "base.png"); // Measure processing time with DirectBitmap - var stopwatch = new Stopwatch(); + Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); ProcessWithDirectBitmap(imagePath); stopwatch.Stop(); - var directBitmapTime = stopwatch.ElapsedMilliseconds; + long directBitmapTime = stopwatch.ElapsedMilliseconds; - // Measure processing time with SkiaSharp - stopwatch.Reset(); - stopwatch.Start(); - var img2 = Tester.ProcessWithSkiaSharp(imagePath); - stopwatch.Stop(); - var skiaTime = stopwatch.ElapsedMilliseconds; // Log times for comparison Console.WriteLine($"DirectBitmap processing time: {directBitmapTime} ms"); - Console.WriteLine($"SkiaSharp processing time: {skiaTime} ms"); - - // Assert: Compare times and choose which one is faster - Assert.IsTrue(directBitmapTime <= skiaTime, "DirectBitmap should be faster or equal in processing time."); } private void ProcessWithDirectBitmap(string imagePath) { var btm = new Bitmap(imagePath); // Load the image using DirectBitmap (replace with your method) - var directBitmap = new DirectBitmap(btm); + DirectBitmap directBitmap = new DirectBitmap(btm); // Example operation: convert to grayscale - for (var x = 0; x < directBitmap.Width; x++) + for (int x = 0; x < directBitmap.Width; x++) { - for (var y = 0; y < directBitmap.Height; y++) + for (int y = 0; y < directBitmap.Height; y++) { - var color = directBitmap.GetPixel(x, y); - var grayValue = (int)((color.R * 0.3) + (color.G * 0.59) + (color.B * 0.11)); + Color color = directBitmap.GetPixel(x, y); + int grayValue = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11); directBitmap.SetPixel(x, y, Color.FromArgb(grayValue, grayValue, grayValue)); } } diff --git a/ImageCompare/AnalysisProcessing.cs b/ImageCompare/AnalysisProcessing.cs index a4b4a814..b11fa37d 100644 --- a/ImageCompare/AnalysisProcessing.cs +++ b/ImageCompare/AnalysisProcessing.cs @@ -38,23 +38,14 @@ internal static class AnalysisProcessing [return: MaybeNull] internal static List GetSimilarity(List imagePaths) { - if (imagePaths.IsNullOrEmpty()) - { - return null; - } + if (imagePaths.IsNullOrEmpty()) return null; - if (imagePaths.Count == 1) - { - return null; - } + if (imagePaths.Count == 1) return null; var paths = new List(imagePaths); var path = imagePaths[0]; - if (!File.Exists(path)) - { - return null; - } + if (!File.Exists(path)) return null; var lst = new List(paths.Count - 1); @@ -66,7 +57,6 @@ internal static List GetSimilarity(List imagePaths) //with sanity check in Case one file went missing, we won't have to stop everything foreach (var element in paths.Where(File.Exists)) - { try { using var btm = new Bitmap(element); @@ -81,7 +71,6 @@ internal static List GetSimilarity(List imagePaths) Trace.WriteLine(ex); throw new InvalidOperationException(ex.ToString()); } - } } catch (InvalidOperationException ex) { @@ -91,10 +80,7 @@ internal static List GetSimilarity(List imagePaths) } //File was skipped? Return null - if (lst.Count != imagePaths.Count - 1) - { - return null; - } + if (lst.Count != imagePaths.Count - 1) return null; lst.AddFirst(100); return lst; @@ -178,10 +164,7 @@ internal static Dictionary GetColors(Bitmap image) [return: MaybeNull] internal static ImageData GetImageDetails(string imagePath) { - if (!File.Exists(imagePath)) - { - return null; - } + if (!File.Exists(imagePath)) return null; using var btm = new Bitmap(imagePath); var color = GenerateData(btm, string.Empty); @@ -251,14 +234,11 @@ internal static Bitmap DifferenceImage(Bitmap first, Bitmap second, Color color) for (var x = 0; x < width; x++) { var index = offset + x; - if (canvasPixels[index] != comparePixels[index]) - { - canvasPixels[index] = colorArgb; - } + if (canvasPixels[index] != comparePixels[index]) canvasPixels[index] = colorArgb; } }); return dbmCanvas.Bitmap; } } -} +} \ No newline at end of file diff --git a/ImageCompare/IImageAnalysis.cs b/ImageCompare/IImageAnalysis.cs index 27812329..6dcfce23 100644 --- a/ImageCompare/IImageAnalysis.cs +++ b/ImageCompare/IImageAnalysis.cs @@ -126,4 +126,4 @@ List FindImagesInColorRange(int r, int g, int b, int range, string folde /// bool IsPartOf(string bigImagePath, string smallImagePath, out Coordinate2D startCoordinates, int threshold = 0); } -} +} \ No newline at end of file diff --git a/ImageCompare/IImageCompare.cs b/ImageCompare/IImageCompare.cs index fc8042bf..099df625 100644 --- a/ImageCompare/IImageCompare.cs +++ b/ImageCompare/IImageCompare.cs @@ -43,4 +43,4 @@ List> GetSimilarImages(string folderPath, bool checkSubfolders, List> GetDuplicateImages(string folderPath, bool checkSubfolders, IEnumerable extensions); } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageAnalysis.cs b/ImageCompare/ImageAnalysis.cs index c32bbc35..0339fe8e 100644 --- a/ImageCompare/ImageAnalysis.cs +++ b/ImageCompare/ImageAnalysis.cs @@ -76,16 +76,10 @@ public List GetImageDetails(List imagePaths) lst.AddRange(imagePaths.Select(AnalysisProcessing.GetImageDetails).Where(cache => cache != null)); //File was skipped? Return null - if (lst.Count != imagePaths.Count) - { - return null; - } + if (lst.Count != imagePaths.Count) return null; var similarity = AnalysisProcessing.GetSimilarity(imagePaths); - for (var i = 0; i < lst.Count; i++) - { - lst[i].Similarity = similarity[i]; - } + for (var i = 0; i < lst.Count; i++) lst[i].Similarity = similarity[i]; return lst; } @@ -101,14 +95,10 @@ public List GetImageDetails(List imagePaths) public ImageCompareData CompareImages(Bitmap first, Bitmap second) { if (first == null) - { throw new ArgumentException(string.Concat(ImageResources.ErrorImageEmpty, nameof(first))); - } if (second == null) - { throw new ArgumentException(string.Concat(ImageResources.ErrorImageEmpty, nameof(second))); - } return ImageHelper.CompareImages(first, second); } @@ -135,10 +125,7 @@ public ImageCompareData CompareImages(string first, string second) /// Argument Exception public Dictionary GetColors(string path) { - if (!File.Exists(path)) - { - throw new ArgumentException(string.Concat(ImageResources.ErrorFileNotFound, path)); - } + if (!File.Exists(path)) throw new ArgumentException(string.Concat(ImageResources.ErrorFileNotFound, path)); var image = new Bitmap(path); @@ -155,9 +142,7 @@ public Dictionary GetColors(string path) public Dictionary GetColors(Bitmap image) { if (image == null) - { throw new ArgumentException(string.Concat(ImageResources.ErrorImageEmpty, nameof(image))); - } return AnalysisProcessing.GetColors(image); } @@ -176,14 +161,10 @@ public Dictionary GetColors(Bitmap image) public Bitmap DifferenceImage(Bitmap first, Bitmap second, Color color) { if (first == null) - { throw new ArgumentException(string.Concat(ImageResources.ErrorImageEmpty, nameof(first))); - } if (second == null) - { throw new ArgumentException(string.Concat(ImageResources.ErrorImageEmpty, nameof(second))); - } return AnalysisProcessing.DifferenceImage(first, second, color); } @@ -220,4 +201,4 @@ public bool IsPartOf(string bigImagePath, string smallImagePath, out Coordinate2 return ImageSlider.IsPartOf(bigImagePath, smallImagePath, out startCoordinates, threshold); } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageColor.cs b/ImageCompare/ImageColor.cs index 25fa70c1..3be54bcb 100644 --- a/ImageCompare/ImageColor.cs +++ b/ImageCompare/ImageColor.cs @@ -102,20 +102,11 @@ public override string ToString() /// public int CompareTo(ImageColor other) { - if (!other.R.Interval(R, Threshold)) - { - return 0; - } + if (!other.R.Interval(R, Threshold)) return 0; - if (!other.G.Interval(G, Threshold)) - { - return 0; - } + if (!other.G.Interval(G, Threshold)) return 0; - if (!other.B.Interval(B, Threshold)) - { - return 0; - } + if (!other.B.Interval(B, Threshold)) return 0; return 1; } @@ -131,20 +122,11 @@ public int CompareTo(ImageColor other) /// public bool Equals(ImageColor other) { - if (!other.R.Interval(R, Threshold)) - { - return false; - } + if (!other.R.Interval(R, Threshold)) return false; - if (!other.G.Interval(G, Threshold)) - { - return false; - } + if (!other.G.Interval(G, Threshold)) return false; - if (!other.B.Interval(B, Threshold)) - { - return false; - } + if (!other.B.Interval(B, Threshold)) return false; return true; } @@ -175,4 +157,4 @@ public bool Equals(ImageColor other) return !(left == right); } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageColoring.cs b/ImageCompare/ImageColoring.cs index d160111b..03c00a3b 100644 --- a/ImageCompare/ImageColoring.cs +++ b/ImageCompare/ImageColoring.cs @@ -49,17 +49,11 @@ internal static List GetSimilarColors(int r, int g, int b, int range, st //create Directories var imagePaths = FileHandleSearch.GetFilesByExtensionFullPath(folderPath, extensions, checkSubfolders); - if (imagePaths.IsNullOrEmpty()) - { - return null; - } + if (imagePaths.IsNullOrEmpty()) return null; var images = GetSortedColorValues(imagePaths); - if (images.IsNullOrEmpty()) - { - return null; - } + if (images.IsNullOrEmpty()) return null; //Generate Image we compare to var dup = new ImageColor { R = r, G = g, B = b, Threshold = range }; @@ -85,7 +79,6 @@ private static List GetSortedColorValues(IReadOnlyCollection //with sanity check in Case one file went missing, we won't have to stop everything foreach (var path in imagePaths.Where(File.Exists)) - { try { using var btm = new Bitmap(path); @@ -102,9 +95,8 @@ private static List GetSortedColorValues(IReadOnlyCollection Trace.WriteLine(ex); throw new InvalidOperationException(ex.Message); } - } return imagePathsAndGrayValues; } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageCompare.cs b/ImageCompare/ImageCompare.cs index 8de53bd2..d7a0b306 100644 --- a/ImageCompare/ImageCompare.cs +++ b/ImageCompare/ImageCompare.cs @@ -54,4 +54,4 @@ public List> GetDuplicateImages(string folderPath, bool checkSubfol return ImageDuplication.GetDuplicateImages(folderPath, checkSubfolders, extensions); } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageCompareData.cs b/ImageCompare/ImageCompareData.cs index b6f83276..4515eddc 100644 --- a/ImageCompare/ImageCompareData.cs +++ b/ImageCompare/ImageCompareData.cs @@ -40,4 +40,4 @@ public sealed class ImageCompareData /// public double Similarity { get; init; } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageData.cs b/ImageCompare/ImageData.cs index 13dce79c..60e8f940 100644 --- a/ImageCompare/ImageData.cs +++ b/ImageCompare/ImageData.cs @@ -118,4 +118,4 @@ public string GetDetailsSimple() ImageResources.ImageSize, Height * Width); } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageDuplicate.cs b/ImageCompare/ImageDuplicate.cs index 48846301..b2405e3d 100644 --- a/ImageCompare/ImageDuplicate.cs +++ b/ImageCompare/ImageDuplicate.cs @@ -80,19 +80,13 @@ public override bool Equals(object obj) /// public bool Equals(ImageDuplicate other) { - if (Image == null || other.Image == null) - { - return false; - } + if (Image == null || other.Image == null) return false; for (var y = 0; y < ImageResources.DuplicateSize; y++) for (var x = 0; x < ImageResources.DuplicateSize; x++) { var comparisonResult = Image[x, y].CompareTo(other.Image[x, y]); - if (comparisonResult != 0) - { - return false; - } + if (comparisonResult != 0) return false; } return other.R.Interval(R, ImageResources.ColorThreshold) && @@ -110,19 +104,13 @@ public bool Equals(ImageDuplicate other) /// public int CompareTo(ImageDuplicate other) { - if (Image == null) - { - return 0; - } + if (Image == null) return 0; for (var i = 0; i < ImageResources.DuplicateSize; i++) for (var j = 0; j < ImageResources.DuplicateSize; j++) { var comparisonResult = Image[i, j].CompareTo(other.Image[i, j]); - if (comparisonResult != 0) - { - return comparisonResult; - } + if (comparisonResult != 0) return comparisonResult; } return 0; @@ -165,4 +153,4 @@ public override int GetHashCode() return !(left == right); } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageDuplication.cs b/ImageCompare/ImageDuplication.cs index 2b066720..f0fbc6eb 100644 --- a/ImageCompare/ImageDuplication.cs +++ b/ImageCompare/ImageDuplication.cs @@ -57,10 +57,7 @@ internal static List> GetDuplicateImages(string folderPath, bool ch //create Directories var imagePaths = FileHandleSearch.GetFilesByExtensionFullPath(folderPath, extensions, checkSubfolders); - if (imagePaths.IsNullOrEmpty()) - { - return null; - } + if (imagePaths.IsNullOrEmpty()) return null; Translator = imagePaths.ToDictionary(); @@ -91,7 +88,6 @@ private static List GetSortedGrayScaleValues() //with sanity check in Case one file went missing, we won't have to stop everything foreach (var (key, value) in Translator.Where(pathImage => File.Exists(pathImage.Value))) - { try { using var btm = new Bitmap(value); @@ -114,7 +110,6 @@ private static List GetSortedGrayScaleValues() Trace.WriteLine(ex); throw new InvalidOperationException(ex.Message); } - } return imagePathsAndGrayValues; } @@ -149,10 +144,7 @@ private static IEnumerable> GetDuplicateGroups( currentDuplicates.Add(image); } - if (currentDuplicates.Count > 1) - { - duplicateGroups.Add(currentDuplicates); - } + if (currentDuplicates.Count > 1) duplicateGroups.Add(currentDuplicates); return duplicateGroups; } @@ -237,4 +229,4 @@ private static List> Translate(IEnumerable> du .ToList(); } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageHelper.cs b/ImageCompare/ImageHelper.cs index b3aea331..ce75c535 100644 --- a/ImageCompare/ImageHelper.cs +++ b/ImageCompare/ImageHelper.cs @@ -47,14 +47,10 @@ internal static ImageCompareData CompareImages(Bitmap first, Bitmap second) internal static ImageCompareData CompareImages(string first, string second) { if (!File.Exists(first)) - { throw new ArgumentException(string.Concat(ImageResources.ErrorFileNotFound, first)); - } if (!File.Exists(second)) - { throw new ArgumentException(string.Concat(ImageResources.ErrorFileNotFound, second)); - } var one = new Bitmap(first); var two = new Bitmap(second); @@ -70,4 +66,4 @@ internal static ImageCompareData CompareImages(string first, string second) }; } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageProcessing.cs b/ImageCompare/ImageProcessing.cs index 48e993c8..a193a15a 100644 --- a/ImageCompare/ImageProcessing.cs +++ b/ImageCompare/ImageProcessing.cs @@ -46,16 +46,10 @@ internal static List FindSimilarImages(ImageSimilar imageToCompare { var percentageDiff = GetPercentageDifference(image, imageToCompareTo); - if (percentageDiff >= maximumDifferenceInPercentage) - { - similarImagesFound.Add(image); - } + if (percentageDiff >= maximumDifferenceInPercentage) similarImagesFound.Add(image); }); - if (similarImagesFound.IsNullOrEmpty()) - { - return null; - } + if (similarImagesFound.IsNullOrEmpty()) return null; return similarImagesFound.Count == 1 ? null : similarImagesFound; } @@ -92,9 +86,9 @@ internal static ImageSimilar GenerateData(Bitmap bitmap, int id) var pixel = dbm.GetPixel(x, y); // Calculate grayscale value - var grayValue = (byte)((pixel.R * 0.299) + (pixel.G * 0.587) + (pixel.B * 0.114)); + var grayValue = (byte)(pixel.R * 0.299 + pixel.G * 0.587 + pixel.B * 0.114); image[x, y] = grayValue; // Store grayscale value - hash[(y * ImageResources.DuplicateSize) + x] = grayValue; // Store grayscale value for hash + hash[y * ImageResources.DuplicateSize + x] = grayValue; // Store grayscale value for hash // Accumulate RGB values based on grayscale contribution r += pixel.R * 0.299; @@ -136,21 +130,18 @@ internal static float GetPercentageDifference(ImageSimilar imageToCompareTo, Ima int one = imageToCompareTo.Image[x, y]; int two = targetBitmap.Image[x, y]; - if (one.Interval(two, ImageResources.ColorThreshold)) - { - diff++; - } + if (one.Interval(two, ImageResources.ColorThreshold)) diff++; } var pixel = (float)diff / ImageResources.MaxPixel * 100; var color = (float) - (((ImageResources.MaxColor - Math.Abs(imageToCompareTo.R - targetBitmap.R)) / ImageResources.MaxColor) + - ((ImageResources.MaxColor - Math.Abs(imageToCompareTo.G - targetBitmap.G)) / ImageResources.MaxColor) + - ((ImageResources.MaxColor - Math.Abs(imageToCompareTo.B - targetBitmap.B)) / - ImageResources.MaxColor)) / 3 * 100; + ((ImageResources.MaxColor - Math.Abs(imageToCompareTo.R - targetBitmap.R)) / ImageResources.MaxColor + + (ImageResources.MaxColor - Math.Abs(imageToCompareTo.G - targetBitmap.G)) / ImageResources.MaxColor + + (ImageResources.MaxColor - Math.Abs(imageToCompareTo.B - targetBitmap.B)) / + ImageResources.MaxColor) / 3 * 100; return (pixel + color) / 2; } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageResources.cs b/ImageCompare/ImageResources.cs index 6975c801..e0570ea2 100644 --- a/ImageCompare/ImageResources.cs +++ b/ImageCompare/ImageResources.cs @@ -78,4 +78,4 @@ internal static class ImageResources /// internal const string Separator = " , "; } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageSimilar.cs b/ImageCompare/ImageSimilar.cs index ba811170..79ee6009 100644 --- a/ImageCompare/ImageSimilar.cs +++ b/ImageCompare/ImageSimilar.cs @@ -113,25 +113,13 @@ public bool Equals(ImageSimilar other) /// public int CompareTo(ImageSimilar other) { - if (Image == null) - { - return 0; - } - - if (!other.R.Interval(R, ImageResources.ColorThreshold)) - { - return 0; - } - - if (!other.G.Interval(G, ImageResources.ColorThreshold)) - { - return 0; - } - - if (!other.B.Interval(B, ImageResources.ColorThreshold)) - { - return 0; - } + if (Image == null) return 0; + + if (!other.R.Interval(R, ImageResources.ColorThreshold)) return 0; + + if (!other.G.Interval(G, ImageResources.ColorThreshold)) return 0; + + if (!other.B.Interval(B, ImageResources.ColorThreshold)) return 0; return 1; } @@ -162,4 +150,4 @@ public int CompareTo(ImageSimilar other) return !(left == right); } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageSimilarity.cs b/ImageCompare/ImageSimilarity.cs index c3eb9f66..33b0ddc8 100644 --- a/ImageCompare/ImageSimilarity.cs +++ b/ImageCompare/ImageSimilarity.cs @@ -50,19 +50,13 @@ internal static List> GetSimilarImages(string folderPath, bool chec //create Directories var imagePaths = FileHandleSearch.GetFilesByExtensionFullPath(folderPath, extensions, checkSubfolders); - if (imagePaths.IsNullOrEmpty()) - { - return null; - } + if (imagePaths.IsNullOrEmpty()) return null; Translator = imagePaths.ToDictionary(); var images = GetSortedGrayScaleValues(); - if (images.IsNullOrEmpty()) - { - return null; - } + if (images.IsNullOrEmpty()) return null; //Just get all Images that are in the same Color Space var duplicateGroups = GetDuplicateGroups(images); @@ -72,10 +66,7 @@ internal static List> GetSimilarImages(string folderPath, bool chec Trace.WriteLine(nameof(duplicateGroups.Count)); //Let's compare all result sets, oif empty well tough luck - if (duplicateGroups.IsNullOrEmpty()) - { - return null; - } + if (duplicateGroups.IsNullOrEmpty()) return null; Trace.WriteLine(duplicateGroups.Count); @@ -96,10 +87,7 @@ internal static List> GetSimilarImages(string folderPath, bool chec localDate = DateTime.Now; Trace.WriteLine(localDate.ToString(CultureInfo.InvariantCulture)); - if (groups.IsNullOrEmpty()) - { - return null; - } + if (groups.IsNullOrEmpty()) return null; var result = Translate(groups); @@ -124,7 +112,6 @@ private static List GetSortedGrayScaleValues() //with sanity check in Case one file went missing, we won't have to stop everything foreach (var (key, value) in Translator.Where(pathImage => File.Exists(pathImage.Value))) - { try { using var btm = new Bitmap(value); @@ -146,7 +133,6 @@ private static List GetSortedGrayScaleValues() Trace.WriteLine(ex); throw new InvalidOperationException(ex.Message); } - } Trace.WriteLine(nameof(GetSortedGrayScaleValues)); Trace.WriteLine(imagePathsAndGrayValues.Count); @@ -200,4 +186,4 @@ private static List> Translate(IEnumerable> dupl .ToList(); } } -} +} \ No newline at end of file diff --git a/ImageCompare/ImageSlider.cs b/ImageCompare/ImageSlider.cs index c42ed140..3dca3149 100644 --- a/ImageCompare/ImageSlider.cs +++ b/ImageCompare/ImageSlider.cs @@ -64,9 +64,7 @@ internal static bool IsPartOf(Bitmap bigImage, Bitmap smallImage, out Coordinate { // Update the bottom edge for the current position in the big image for (var x = 0; x < smallWidth; x++) - { smallImageBottomEdge.SetPixel(x, 0, dbmBig.GetPixel(j + x, i + smallHeight - 1)); - } if (CheckEdges(dbmBig, dbmSmall, i, j, smallImageBottomEdge, threshold) && CheckFull(dbmBig, dbmSmall, i, j, threshold)) @@ -100,41 +98,25 @@ private static bool CheckEdges(DirectBitmap bigImage, DirectBitmap smallImage, i // Check top edge for (var x = 0; x < smallWidth; x++) - { if (!IsColorMatch(bigImage.GetPixel(startCol + x, startRow), smallImage.GetPixel(x, 0), threshold)) - { return false; - } - } // Check bottom edge for (var x = 0; x < smallWidth; x++) - { if (!IsColorMatch(bigImage.GetPixel(startCol + x, startRow + smallHeight - 1), smallImageBottomEdge.GetPixel(x, 0), threshold)) - { return false; - } - } // Check left edge for (var y = 0; y < smallHeight; y++) - { if (!IsColorMatch(bigImage.GetPixel(startCol, startRow + y), smallImage.GetPixel(0, y), threshold)) - { return false; - } - } // Check right edge for (var y = 0; y < smallHeight; y++) - { if (!IsColorMatch(bigImage.GetPixel(startCol + smallWidth - 1, startRow + y), smallImage.GetPixel(smallWidth - 1, y), threshold)) - { return false; - } - } return true; } @@ -158,13 +140,9 @@ private static bool CheckFull(DirectBitmap bigImage, DirectBitmap smallImage, in for (var y = 0; y < smallHeight; y++) for (var x = 0; x < smallWidth; x++) - { if (!IsColorMatch(bigImage.GetPixel(startCol + x, startRow + y), smallImage.GetPixel(x, y), threshold)) - { return false; - } - } return true; } @@ -185,4 +163,4 @@ private static bool IsColorMatch(Color color1, Color color2, int threshold) Math.Abs(color1.B - color2.B) <= threshold; } } -} +} \ No newline at end of file diff --git a/Imaging/Cif.cs b/Imaging/Cif.cs index 4e7ce93b..9f7fa1f3 100644 --- a/Imaging/Cif.cs +++ b/Imaging/Cif.cs @@ -50,14 +50,9 @@ public sealed class Cif public Cif(string path, ICustomImageFormat imageFormat) { if (imageFormat == null) - { throw new ArgumentNullException(nameof(imageFormat), ImagingResources.ErrorInterface); - } - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentException(ImagingResources.ErrorPath, nameof(path)); - } + if (string.IsNullOrEmpty(path)) throw new ArgumentException(ImagingResources.ErrorPath, nameof(path)); var cif = imageFormat.GetCif(path); @@ -77,15 +72,9 @@ public Cif(string path, ICustomImageFormat imageFormat) /// Image was null. - image public Cif(Bitmap image, ICustomImageFormat imageFormat = null) { - if (image == null) - { - throw new ArgumentNullException(nameof(image), ImagingResources.ErrorImage); - } + if (image == null) throw new ArgumentNullException(nameof(image), ImagingResources.ErrorImage); - if (imageFormat != null) - { - ImageFormat = imageFormat; - } + if (imageFormat != null) ImageFormat = imageFormat; Height = image.Height; Width = image.Width; @@ -112,10 +101,7 @@ public Cif(Bitmap image, ICustomImageFormat imageFormat = null) /// The custom image format. public Cif(ICustomImageFormat imageFormat = null) { - if (imageFormat != null) - { - ImageFormat = imageFormat; - } + if (imageFormat != null) ImageFormat = imageFormat; Compressed = false; } @@ -217,22 +203,13 @@ public bool ChangeColor(int x, int y, Color color) var coordinate = new Coordinate2D(x, y, Width); var id = coordinate.Id; - if (id > CheckSum) - { - return false; - } + if (id > CheckSum) return false; foreach (var (key, value) in CifImage) { - if (!value.Contains(id)) - { - continue; - } + if (!value.Contains(id)) continue; - if (key == color) - { - return false; - } + if (key == color) return false; CifImage[key].Remove(id); @@ -260,22 +237,15 @@ public bool ChangeColor(int x, int y, Color color) /// Success Status public bool ChangeColor(Color oldColor, Color newColor) { - if (!CifImage.ContainsKey(oldColor)) - { - return false; - } + if (!CifImage.ContainsKey(oldColor)) return false; var cache = CifImage[oldColor]; CifImage.Remove(oldColor); if (CifImage.ContainsKey(newColor)) - { CifImage[newColor].UnionWith(cache); - } else - { CifImage.Add(newColor, cache); - } return true; } @@ -292,9 +262,7 @@ public bool ChangeColor(Color oldColor, Color newColor) public Color GetColor(int id) { if (id < 0 || id > Height * Width) - { throw new ArgumentOutOfRangeException(nameof(id), ImagingResources.ErrorInterface); - } // Check if sorting is required and perform lazy loading if (_sortRequired) @@ -304,12 +272,8 @@ public Color GetColor(int id) } foreach (var (color, value) in _cifSorted) - { if (value.Contains(id)) - { return color; - } - } throw new KeyNotFoundException(nameof(id)); } @@ -321,19 +285,14 @@ public Color GetColor(int id) [return: MaybeNull] public Bitmap GetImage() { - if (CifImage == null) - { - return null; - } + if (CifImage == null) return null; var image = new Bitmap(Height, Width); var dbm = DirectBitmap.GetInstance(image); foreach (var (key, value) in CifImage) foreach (var coordinate in value.Select(id => Coordinate2D.GetInstance(id, Width))) - { dbm.SetPixel(coordinate.X, coordinate.Y, key); - } return dbm.Bitmap; } @@ -355,9 +314,7 @@ public override string ToString() var sortedList = new List(value); for (var i = 0; i < value.Count - 1; i++) - { info = string.Concat(info, sortedList[i], ImagingResources.Indexer); - } info = string.Concat(info, sortedList[sortedList.Count], Environment.NewLine); } @@ -384,10 +341,7 @@ private Dictionary GetColorCount() { var colorCount = new Dictionary(NumberOfColors); - foreach (var (color, sortedSet) in CifImage) - { - colorCount.Add(color, sortedSet.Count); - } + foreach (var (color, sortedSet) in CifImage) colorCount.Add(color, sortedSet.Count); // Sort the dictionary by value in descending order return colorCount.OrderByDescending(kv => kv.Value).ToDictionary(kv => kv.Key, kv => kv.Value); @@ -402,10 +356,7 @@ private Dictionary GetColorCount() /// private void Dispose(bool disposing) { - if (Disposed) - { - return; - } + if (Disposed) return; if (disposing) { @@ -442,4 +393,4 @@ private static Dictionary> SortDct(Dictionary kv.Key, kv => kv.Value); } } -} +} \ No newline at end of file diff --git a/Imaging/CifImageData.cs b/Imaging/CifImageData.cs index 15ab8c6b..a47e53ca 100644 --- a/Imaging/CifImageData.cs +++ b/Imaging/CifImageData.cs @@ -23,41 +23,29 @@ internal sealed class CifImageData internal static readonly Func, CifImageData> Converter = parts => { var hex = parts[0]; - if (!int.TryParse(parts[1], out var a)) - { - return null; - } + if (!int.TryParse(parts[1], out var a)) return null; var converter = new ColorHsv(hex, a); var color = Color.FromArgb((byte)converter.A, (byte)converter.R, (byte)converter.G, (byte)converter.B); var coordinates = new List(); for (var i = 2; i < parts.Count; i++) - { if (parts[i].Contains(ImagingResources.IntervalSplitter)) { var lst = parts[i].Split(ImagingResources.CifSeparator).ToList(); var sequence = GetStartEndPoint(lst); - if (sequence == null) - { - continue; - } + if (sequence == null) continue; // Ensure Start and End are not null before casting if (sequence.Value.Start.HasValue && sequence.Value.End.HasValue) - { for (var id = sequence.Value.Start.Value; id <= sequence.Value.End.Value; id++) - { coordinates.Add(id); - } - } } else if (int.TryParse(parts[i], out var idMaster)) { coordinates.Add(idMaster); } - } return new CifImageData { Color = color, Coordinates = coordinates }; }; @@ -85,10 +73,7 @@ internal sealed class CifImageData /// A tuple representing the start and end points, or null if parsing fails. private static (int? Start, int? End)? GetStartEndPoint(IReadOnlyList lst) { - if (lst.Count < 2) - { - return null; - } + if (lst.Count < 2) return null; var checkStart = int.TryParse(lst[0], out var start); var checkEnd = int.TryParse(lst[1], out var end); @@ -96,4 +81,4 @@ private static (int? Start, int? End)? GetStartEndPoint(IReadOnlyList ls return checkStart && checkEnd ? (start, end) : null; } } -} +} \ No newline at end of file diff --git a/Imaging/CifMetadata.cs b/Imaging/CifMetadata.cs index 004623ea..a7c7b8bb 100644 --- a/Imaging/CifMetadata.cs +++ b/Imaging/CifMetadata.cs @@ -24,7 +24,6 @@ public sealed class CifMetadata { if (int.TryParse(parts[0], out var height) && int.TryParse(parts[1], out var width) && int.TryParse(parts[3], out var checkSum)) - { return new CifMetadata { Height = height, @@ -32,7 +31,6 @@ public sealed class CifMetadata Compressed = parts[2] == ImagingResources.CifCompressed, CheckSum = checkSum }; - } return null; }; @@ -63,4 +61,4 @@ public sealed class CifMetadata /// public int CheckSum { get; set; } } -} +} \ No newline at end of file diff --git a/Imaging/CifProcessing.cs b/Imaging/CifProcessing.cs index c115112e..463cddef 100644 --- a/Imaging/CifProcessing.cs +++ b/Imaging/CifProcessing.cs @@ -39,10 +39,7 @@ internal static Dictionary> ConvertToCifFromBitmap(Bitmap { var color = colorMap[i]; - if (!imageFormat.ContainsKey(color)) - { - imageFormat[color] = new SortedSet(); - } + if (!imageFormat.ContainsKey(color)) imageFormat[color] = new SortedSet(); imageFormat[color].Add(i); } @@ -58,19 +55,13 @@ internal static Dictionary> ConvertToCifFromBitmap(Bitmap internal static Bitmap? CifFileToImage(string path) { var cif = CifFromFile(path); - if (cif == null) - { - return null; - } + if (cif == null) return null; var image = new Bitmap(cif.Width, cif.Height); var dbm = DirectBitmap.GetInstance(image); - foreach (var (color, ids) in cif.CifImage) - { - dbm.SetArea(ids, color); - } + foreach (var (color, ids) in cif.CifImage) dbm.SetArea(ids, color); return dbm.Bitmap; } @@ -93,18 +84,13 @@ internal static Dictionary> ConvertToCifFromBitmap(Bitmap var csvData = new List(); foreach (var (converter, startLine, endLine) in ranges) - { csvData.AddRange(CsvHandler.ReadCsvRange(path, ImagingResources.Separator, converter, startLine, endLine)); - } var meta = csvData.OfType().FirstOrDefault(); var imageData = csvData.OfType().ToList(); - if (meta == null) - { - return null; - } + if (meta == null) return null; var cif = new Cif { @@ -116,15 +102,9 @@ internal static Dictionary> ConvertToCifFromBitmap(Bitmap foreach (var data in imageData) { - if (!cif.CifImage.ContainsKey(data.Color)) - { - cif.CifImage[data.Color] = new SortedSet(); - } + if (!cif.CifImage.ContainsKey(data.Color)) cif.CifImage[data.Color] = new SortedSet(); - foreach (var coordinates in data.Coordinates) - { - cif.CifImage[data.Color].Add(coordinates); - } + foreach (var coordinates in data.Coordinates) cif.CifImage[data.Color].Add(coordinates); } return cif; @@ -204,10 +184,7 @@ internal static List> GenerateCsvCompressed(int imageHeight, int im var compressed = new List(); - if (sequence == null) - { - continue; - } + if (sequence == null) continue; var sortedList = new List(value); @@ -236,4 +213,4 @@ internal static List> GenerateCsvCompressed(int imageHeight, int im return master; } } -} +} \ No newline at end of file diff --git a/Imaging/ColorHsv.cs b/Imaging/ColorHsv.cs index f1f755e9..b76d603f 100644 --- a/Imaging/ColorHsv.cs +++ b/Imaging/ColorHsv.cs @@ -59,20 +59,11 @@ public ColorHsv(double h, double s, double v, int a) /// The Hue value. public ColorHsv(int r, int g, int b, int a) { - if (r == -1) - { - return; - } + if (r == -1) return; - if (g == -1) - { - return; - } + if (g == -1) return; - if (b == -1) - { - return; - } + if (b == -1) return; ColorToHsv(r, g, b, a); } @@ -136,25 +127,13 @@ public ColorHsv(string hex, int a) /// If equal or not public bool Equals(ColorHsv other) { - if (other == null) - { - return false; - } + if (other == null) return false; - if (R != other.R) - { - return false; - } + if (R != other.R) return false; - if (G != other.G) - { - return false; - } + if (G != other.G) return false; - if (B != other.B) - { - return false; - } + if (B != other.B) return false; return A == other.A; } @@ -176,13 +155,10 @@ public void RgbFromHsv(double h, double s, double v, int a) var degree = h * 180 / Math.PI; - if (degree is > 360 or < 0 || s is > 1 or < 0 || v is > 1 or < 0) - { - return; - } + if (degree is > 360 or < 0 || s is > 1 or < 0 || v is > 1 or < 0) return; var c = v * s; - var x = c * (1 - Math.Abs((degree / 60 % 2) - 1)); + var x = c * (1 - Math.Abs(degree / 60 % 2 - 1)); var m = v - c; double r = 0, g = 0, b = 0; @@ -236,10 +212,7 @@ public void RgbFromHsv(double h, double s, double v, int a) /// The hexadecimal. public void RbgHex(string hex) { - if (string.IsNullOrEmpty(hex)) - { - return; - } + if (string.IsNullOrEmpty(hex)) return; Color color; @@ -275,7 +248,7 @@ public void ColorToHsv(int r, int g, int b, int a) var min = Math.Min(r, Math.Min(g, b)); H = GetHue(r, g, b); - S = max == 0 ? 0 : 1d - (1d * min / max); + S = max == 0 ? 0 : 1d - 1d * min / max; V = max / 255d; GetHex(); @@ -299,7 +272,7 @@ public void ColorToHsv(int color) // Calculate the hue, saturation, and value H = GetHue(R, G, B); - S = max == 0 ? 0 : 1d - (1d * min / max); + S = max == 0 ? 0 : 1d - 1d * min / max; V = max / 255d; // Update the hex representation of the color @@ -313,10 +286,7 @@ public void ColorToHsv(int color) /// The hexadecimal. public void HexToColor(string hex) { - if (string.IsNullOrEmpty(hex)) - { - return; - } + if (string.IsNullOrEmpty(hex)) return; var color = (Color)ColorConverter.ConvertFromString(hex); @@ -376,15 +346,8 @@ public override int GetHashCode() /// public static bool operator ==(ColorHsv left, ColorHsv right) { - if (ReferenceEquals(left, right)) - { - return true; // Same reference - } - - if (left is null || right is null) - { - return false; // One is null - } + if (ReferenceEquals(left, right)) return true; // Same reference + if (left is null || right is null) return false; // One is null return left.Equals(right); } @@ -434,32 +397,20 @@ private static double GetHue(int r, int g, int b) double min = Math.Min(Math.Min(r, g), b); double max = Math.Max(Math.Max(r, g), b); - if (min.IsEqualTo(max, 10)) - { - return 0; - } + if (min.IsEqualTo(max, 10)) return 0; double hue; if (max.IsEqualTo(r, 10)) - { hue = (g - b) / (max - min); - } else if (max.IsEqualTo(g, 10)) - { - hue = 2f + ((b - r) / (max - min)); - } + hue = 2f + (b - r) / (max - min); else - { - hue = 4f + ((r - g) / (max - min)); - } + hue = 4f + (r - g) / (max - min); hue *= 60; - if (hue < 0) - { - hue += 360; - } + if (hue < 0) hue += 360; return hue * Math.PI / 180; } @@ -484,4 +435,4 @@ public override string ToString() return $"{R:X2} {G:X2} {B:X2}"; } } -} +} \ No newline at end of file diff --git a/Imaging/CustomImageFormat.cs b/Imaging/CustomImageFormat.cs index 48d59791..863819ef 100644 --- a/Imaging/CustomImageFormat.cs +++ b/Imaging/CustomImageFormat.cs @@ -96,4 +96,4 @@ public void GenerateCifCompressedFromBitmap(Bitmap image, string path) CsvHandler.WriteCsv(path, lst); } } -} +} \ No newline at end of file diff --git a/Imaging/DirectBitmap.cs b/Imaging/DirectBitmap.cs index 4d0a6e4f..0e9df0b2 100644 --- a/Imaging/DirectBitmap.cs +++ b/Imaging/DirectBitmap.cs @@ -16,11 +16,15 @@ using System; using System.Collections.Generic; using System.Drawing; -using System.Drawing.Imaging; using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using Color = System.Drawing.Color; +using PixelFormat = System.Drawing.Imaging.PixelFormat; namespace Imaging { @@ -167,10 +171,7 @@ public static DirectBitmap GetInstance(Bitmap btm) public void DrawVerticalLine(int x, int y, int height, Color color) { var colorArgb = color.ToArgb(); - for (var i = y; i < y + height && i < Height; i++) - { - Bits[x + (i * Width)] = colorArgb; - } + for (var i = y; i < y + height && i < Height; i++) Bits[x + i * Width] = colorArgb; } /// @@ -183,10 +184,7 @@ public void DrawVerticalLine(int x, int y, int height, Color color) /// The color. public void DrawHorizontalLine(int x, int y, int length, Color color) { - if (y < 0 || y >= Height || length <= 0) - { - return; - } + if (y < 0 || y >= Height || length <= 0) return; var colorArgb = color.ToArgb(); var vectorCount = Vector.Count; @@ -198,22 +196,14 @@ public void DrawHorizontalLine(int x, int y, int length, Color color) var startX = (x + vectorCount - 1) & ~(vectorCount - 1); // Fill initial non-aligned part - for (var i = x; i < startX && i < endX; i++) - { - Bits[i + (y * Width)] = colorArgb; - } + for (var i = x; i < startX && i < endX; i++) Bits[i + y * Width] = colorArgb; // Fill aligned part with SIMD for (var xPos = startX; xPos + vectorCount <= endX; xPos += vectorCount) - { - colorVector.CopyTo(Bits, xPos + (y * Width)); - } + colorVector.CopyTo(Bits, xPos + y * Width); // Fill final non-aligned part - for (var i = endX - vectorCount; i < endX; i++) - { - Bits[i + (y * Width)] = colorArgb; - } + for (var i = endX - vectorCount; i < endX; i++) Bits[i + y * Width] = colorArgb; } /// @@ -234,18 +224,12 @@ public void DrawRectangle(int x1, int y2, int width, int height, Color color) for (var y = y2; y < y2 + height && y < Height; y++) for (var x = x1; x < x1 + width && x < Width; x += vectorCount) { - var startIndex = x + (y * Width); + var startIndex = x + y * Width; if (startIndex + vectorCount <= Bits.Length) - { colorVector.CopyTo(Bits, startIndex); - } else - { for (var j = 0; j < vectorCount && startIndex + j < Bits.Length; j++) - { Bits[startIndex + j] = colorArgb; - } - } } } @@ -269,22 +253,14 @@ public void SetArea(IEnumerable idList, Color color) var indexVector = new Vector(indices, i); for (var j = 0; j < chunkSize; j++) - { if (indexVector[j] < Bits.Length) - { Bits[indexVector[j]] = colorArgb; - } - } } else { for (var j = i; j < i + chunkSize; j++) - { if (indices[j] < Bits.Length) - { Bits[indices[j]] = colorArgb; - } - } } } } @@ -298,7 +274,7 @@ public void SetArea(IEnumerable idList, Color color) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetPixel(int x, int y, Color color) { - var index = x + (y * Width); + var index = x + y * Width; Bits[index] = color.ToArgb(); } @@ -320,9 +296,7 @@ public void SetPixelsSimd(IEnumerable<(int x, int y, Color color)> pixels) // Ensure Bits array is properly initialized if (Bits == null || Bits.Length < Width * Height) - { throw new InvalidOperationException(ImagingResources.ErrorInvalidOperation); - } for (var i = 0; i < pixelArray.Length; i += vectorCount) { @@ -331,11 +305,10 @@ public void SetPixelsSimd(IEnumerable<(int x, int y, Color color)> pixels) // Load data into vectors for (var j = 0; j < vectorCount; j++) - { if (i + j < pixelArray.Length) { var (x, y, color) = pixelArray[i + j]; - indices[j] = x + (y * Width); + indices[j] = x + y * Width; colors[j] = color.ToArgb(); } else @@ -344,16 +317,11 @@ public void SetPixelsSimd(IEnumerable<(int x, int y, Color color)> pixels) indices[j] = 0; colors[j] = Color.Transparent.ToArgb(); // Use a default color or handle it as needed } - } // Write data to Bits array for (var j = 0; j < vectorCount; j++) - { if (i + j < pixelArray.Length) - { Bits[indices[j]] = colors[j]; - } - } } } @@ -366,7 +334,7 @@ public void SetPixelsSimd(IEnumerable<(int x, int y, Color color)> pixels) [MethodImpl(MethodImplOptions.AggressiveInlining)] public Color GetPixel(int x, int y) { - var index = x + (y * Width); + var index = x + y * Width; var col = Bits[index]; return Color.FromArgb(col); } @@ -377,10 +345,7 @@ public Color GetPixel(int x, int y) /// The Image as a list of Colors public Span GetColors() { - if (Bits == null) - { - return null; - } + if (Bits == null) return null; var length = Height * Width; var array = new Color[length]; @@ -395,6 +360,30 @@ public Span GetColors() return span; } + /// + /// Converts the Bits into bitmapImage. + /// + /// BitmapImage image data + public BitmapImage ToBitmapImage() + { + // Create a WriteableBitmap with the same dimensions as the DirectBitmap + var writeableBitmap = new WriteableBitmap(Width, Height, 96, 96, PixelFormats.Bgra32, null); + + // Write the pixel data (from DirectBitmap's Bits) into the WriteableBitmap + writeableBitmap.WritePixels( + new Int32Rect(0, 0, Width, Height), + Bits, + Width * 4, // Each pixel has 4 bytes (BGRA) + 0); + + // Return the WriteableBitmap as a BitmapImage + return new BitmapImage + { + CreateOptions = BitmapCreateOptions.None, + CacheOption = BitmapCacheOption.OnLoad + }; + } + /// /// Converts to string. /// @@ -405,10 +394,7 @@ public override string ToString() { var info = string.Empty; - for (var i = 0; i < Bits.Length - 1; i++) - { - info = string.Concat(info, Bits[i], ImagingResources.Indexer); - } + for (var i = 0; i < Bits.Length - 1; i++) info = string.Concat(info, Bits[i], ImagingResources.Indexer); return string.Concat(info, ImagingResources.Spacing, Bits[Bits.Length]); } @@ -433,10 +419,7 @@ public override int GetHashCode() /// private void Dispose(bool disposing) { - if (Disposed) - { - return; - } + if (Disposed) return; if (disposing) { @@ -444,10 +427,7 @@ private void Dispose(bool disposing) Bitmap?.Dispose(); // Free the GCHandle if it is allocated - if (BitsHandle.IsAllocated) - { - BitsHandle.Free(); - } + if (BitsHandle.IsAllocated) BitsHandle.Free(); } Disposed = true; @@ -465,4 +445,4 @@ private void Dispose(bool disposing) Dispose(false); } } -} +} \ No newline at end of file diff --git a/Imaging/DirectBitmapImage.cs b/Imaging/DirectBitmapImage.cs index 3995976e..c3ae6772 100644 --- a/Imaging/DirectBitmapImage.cs +++ b/Imaging/DirectBitmapImage.cs @@ -110,12 +110,10 @@ public void SetPixels(IEnumerable pixels) { // Validate pixel bounds if (pixel.X < 0 || pixel.X >= Width || pixel.Y < 0 || pixel.Y >= Height) - { continue; // Skip invalid pixels - } // Calculate the index in the back buffer - var pixelIndex = ((pixel.Y * Width) + pixel.X) * 4; // 4 bytes per pixel (BGRA) + var pixelIndex = (pixel.Y * Width + pixel.X) * 4; // 4 bytes per pixel (BGRA) // Set the pixel data in the back buffer dataPointer[pixelIndex + 0] = pixel.B; // Blue @@ -124,7 +122,7 @@ public void SetPixels(IEnumerable pixels) dataPointer[pixelIndex + 3] = pixel.A; // Alpha // Store the pixel data as ARGB in the Bits array - Bits[(pixel.Y * Width) + pixel.X] = Bits[(pixel.Y * Width) + pixel.X] = + Bits[pixel.Y * Width + pixel.X] = Bits[pixel.Y * Width + pixel.X] = (uint)((pixel.A << 24) | (pixel.R << 16) | (pixel.G << 8) | pixel.B); // This will be fine as long as A, R, G, B are 0-255 } @@ -204,9 +202,7 @@ public void ApplyColorMatrix(float[][] matrix) { result[j] = 0; // Initialize to zero before summation for (var k = 0; k < 4; k++) // Ensure we only sum over valid indices - { result[j] += matrix[j][k] * colorVector[k]; - } } // Clamp result to [0, 255] and convert to bytes @@ -241,9 +237,7 @@ public void SetPixelsSimd(IEnumerable<(int x, int y, Color color)> pixels) // Ensure Bits array is properly initialized if (Bits == null || Bits.Length < Width * Height) - { throw new InvalidOperationException(ImagingResources.ErrorInvalidOperation); - } for (var i = 0; i < pixelArray.Length; i += vectorCount) { @@ -252,7 +246,6 @@ public void SetPixelsSimd(IEnumerable<(int x, int y, Color color)> pixels) // Load data into vectors for (var j = 0; j < vectorCount; j++) - { if (i + j < pixelArray.Length) { var (x, y, color) = pixelArray[i + j]; @@ -260,7 +253,7 @@ public void SetPixelsSimd(IEnumerable<(int x, int y, Color color)> pixels) // Check for valid pixel bounds if (x >= 0 && x < Width && y >= 0 && y < Height) { - indices[j] = x + (y * Width); + indices[j] = x + y * Width; colors[j] = (color.A << 24) | (color.R << 16) | (color.G << 8) | color.B; } else @@ -276,17 +269,12 @@ public void SetPixelsSimd(IEnumerable<(int x, int y, Color color)> pixels) indices[j] = 0; // Default index (can also be an invalid one) colors[j] = 0; // Default color } - } // Write data to Bits array for (var j = 0; j < vectorCount; j++) // Write only valid indices - { if (i + j < pixelArray.Length) - { Bits[indices[j]] = (uint)colors[j]; - } - } } } @@ -319,19 +307,12 @@ public void UpdateBitmapFromBits() /// private void Dispose(bool disposing) { - if (_disposed) - { - return; - } + if (_disposed) return; if (disposing) // Free the GCHandle if allocated - { if (_bitsHandle.IsAllocated) - { _bitsHandle.Free(); - } - } _disposed = true; } @@ -344,4 +325,4 @@ private void Dispose(bool disposing) Dispose(false); } } -} +} \ No newline at end of file diff --git a/Imaging/FiltersAreas.cs b/Imaging/FiltersAreas.cs index f5d6a5cc..45e2d993 100644 --- a/Imaging/FiltersAreas.cs +++ b/Imaging/FiltersAreas.cs @@ -17,7 +17,7 @@ namespace Imaging internal static class FiltersAreas { /// - /// Generates the filter. + /// Generates the filter. /// /// The image. /// The width. @@ -28,13 +28,11 @@ internal static class FiltersAreas /// The shape parameters. /// The optional starting point (top-left corner) of the rectangle. Defaults to (0, 0). /// - /// Generates a filter for a certain area + /// Generates a filter for a certain area /// - /// - /// filter - null - /// or - /// shape - null - /// + /// filter - null + /// or + /// shape - null internal static Bitmap GenerateFilter(Bitmap image, int? width, int? height, @@ -45,16 +43,9 @@ internal static Bitmap GenerateFilter(Bitmap image, Point? startPoint = null) { // Validate input - if (image == null) - { - throw new ArgumentNullException(nameof(image)); - } - - if (filter == FiltersType.None) - { - return image; // No filtering required - } + if (image == null) throw new ArgumentNullException(nameof(image)); + if (filter == FiltersType.None) return image; // No filtering required // Default start point var actualStartPoint = startPoint ?? new Point(0, 0); @@ -63,15 +54,13 @@ internal static Bitmap GenerateFilter(Bitmap image, var actualHeight = height ?? image.Height; // Apply filter - var filterBitmap = FiltersStream.FilterImage(image, filter, imageSettings); + Bitmap filterBitmap = FiltersStream.FilterImage(image, filter, imageSettings); // Apply mask filterBitmap = shape switch { - MaskShape.Rectangle => ImageMask.ApplyRectangleMask(filterBitmap, actualWidth, actualHeight, - actualStartPoint), - MaskShape.Circle => ImageMask.ApplyCircleMask(filterBitmap, actualWidth, actualHeight, - actualStartPoint), + MaskShape.Rectangle => ImageMask.ApplyRectangleMask(filterBitmap, actualWidth, actualHeight, actualStartPoint), + MaskShape.Circle => ImageMask.ApplyCircleMask(filterBitmap, actualWidth, actualHeight, actualStartPoint), MaskShape.Polygon => shapeParams is Point[] points ? ImageMask.ApplyPolygonMask(filterBitmap, points) : throw new ArgumentException(ImagingResources.ErrorWithShapePolygon, nameof(shapeParams)), @@ -82,4 +71,4 @@ internal static Bitmap GenerateFilter(Bitmap image, return ImageStream.CombineBitmap(image, filterBitmap, 0, 0); } } -} +} \ No newline at end of file diff --git a/Imaging/FiltersConfig.cs b/Imaging/FiltersConfig.cs index 0dda54db..540d54d1 100644 --- a/Imaging/FiltersConfig.cs +++ b/Imaging/FiltersConfig.cs @@ -57,4 +57,4 @@ public sealed class FiltersConfig /// public int Scale { get; init; } = 1; } -} +} \ No newline at end of file diff --git a/Imaging/FiltersStream.cs b/Imaging/FiltersStream.cs index 0586f073..249d73d7 100644 --- a/Imaging/FiltersStream.cs +++ b/Imaging/FiltersStream.cs @@ -226,10 +226,7 @@ private static Bitmap ApplyFilter(Image sourceBitmap, double[,] filterMatrix, do var imageY = y + (filterY - filterOffset); // Check bounds to prevent out-of-bounds access - if (imageX < 0 || imageX >= source.Width || imageY < 0 || imageY >= source.Height) - { - continue; - } + if (imageX < 0 || imageX >= source.Width || imageY < 0 || imageY >= source.Height) continue; var pixelColor = source.GetPixel(imageX, imageY); @@ -238,9 +235,9 @@ private static Bitmap ApplyFilter(Image sourceBitmap, double[,] filterMatrix, do red += pixelColor.R * filterMatrix[filterY, filterX]; } - var newBlue = ImageHelper.Clamp((factor * blue) + bias); - var newGreen = ImageHelper.Clamp((factor * green) + bias); - var newRed = ImageHelper.Clamp((factor * red) + bias); + var newBlue = ImageHelper.Clamp(factor * blue + bias); + var newGreen = ImageHelper.Clamp(factor * green + bias); + var newRed = ImageHelper.Clamp(factor * red + bias); // Instead of setting the pixel immediately, add it to the list pixelsToSet.Add((x, y, Color.FromArgb(newRed, newGreen, newBlue))); @@ -342,7 +339,7 @@ private static Bitmap ApplySobel(Bitmap originalImage) } // Calculate gradient magnitude - var magnitude = (int)Math.Sqrt((gx * gx) + (gy * gy)); + var magnitude = (int)Math.Sqrt(gx * gx + gy * gy); // Normalize the magnitude to fit within the range of 0-255 magnitude = ImageHelper.Clamp(magnitude / Math.Sqrt(2)); // Divide by sqrt(2) for normalization @@ -621,7 +618,7 @@ private static void DetermineRegionSizeAndShape(DirectBitmap dbmBase, int x, int // Compute gradient magnitude using Sobel operators var gradientX = ApplyKernel(dbmBase, x, y, _imageSettings.SobelX); var gradientY = ApplyKernel(dbmBase, x, y, _imageSettings.SobelY); - var gradientMagnitude = Math.Sqrt((gradientX * gradientX) + (gradientY * gradientY)); + var gradientMagnitude = Math.Sqrt(gradientX * gradientX + gradientY * gradientY); // Compute local variance var variance = ComputeLocalVariance(dbmBase, x, y, baseHalfWindow); @@ -688,7 +685,7 @@ private static double ComputeLocalVariance(DirectBitmap dbmBase, int x, int y, i } var mean = sum / count; - var variance = (sumSquared / count) - (mean * mean); + var variance = sumSquared / count - mean * mean; return variance; } @@ -787,18 +784,16 @@ private static IEnumerable DefineRegions(int centerX, int centerY, in var regions = new List { // Base region - new(centerX - (width / 2), centerY - (height / 2), width, height) + new(centerX - width / 2, centerY - height / 2, width, height) }; for (var i = 1; i <= 3; i++) // Adding 3 additional regions with varying sizes { - var newWidth = width - (i * step); - var newHeight = height - (i * step); + var newWidth = width - i * step; + var newHeight = height - i * step; if (newWidth > 0 && newHeight > 0) - { - regions.Add(new Rectangle(centerX - (newWidth / 2) + (offset * i), - centerY - (newHeight / 2) + (offset * i), newWidth, newHeight)); - } + regions.Add(new Rectangle(centerX - newWidth / 2 + offset * i, + centerY - newHeight / 2 + offset * i, newWidth, newHeight)); } return regions; @@ -867,7 +862,7 @@ private static void DistributeError(DirectBitmap dbmBase, int x, int y, int erro { var pixel = dbmBase.GetPixel(nx, ny); var oldIntensity = pixel.R; // Since it's grayscale, R=G=B - var newIntensity = ImageHelper.Clamp(oldIntensity + (error * ditherMatrix[dy, dx] / 16)); + var newIntensity = ImageHelper.Clamp(oldIntensity + error * ditherMatrix[dy, dx] / 16); var newColor = Color.FromArgb(newIntensity, newIntensity, newIntensity); pixelsToSet.Add((nx, ny, newColor)); @@ -930,4 +925,4 @@ private static Bitmap SubtractImages(Image imgOne, Image imgTwo) return null; } } -} +} \ No newline at end of file diff --git a/Imaging/FiltersType.cs b/Imaging/FiltersType.cs index 68493525..21f2e025 100644 --- a/Imaging/FiltersType.cs +++ b/Imaging/FiltersType.cs @@ -156,4 +156,4 @@ public enum FiltersType /// PencilSketchEffect = 26 } -} +} \ No newline at end of file diff --git a/Imaging/ICustomImageFormat.cs b/Imaging/ICustomImageFormat.cs index 523ee4f3..05476456 100644 --- a/Imaging/ICustomImageFormat.cs +++ b/Imaging/ICustomImageFormat.cs @@ -53,4 +53,4 @@ public interface ICustomImageFormat /// The path. void GenerateCifCompressedFromBitmap(Bitmap image, string path); } -} +} \ No newline at end of file diff --git a/Imaging/IImageRender.cs b/Imaging/IImageRender.cs index ed62c2bc..91dbb5f0 100644 --- a/Imaging/IImageRender.cs +++ b/Imaging/IImageRender.cs @@ -90,7 +90,7 @@ internal interface IImageRender Bitmap FilterImage(Bitmap image, FiltersType filter); /// - /// Filters the image area. + /// Filters the image area. /// /// The image. /// The width. @@ -100,13 +100,11 @@ internal interface IImageRender /// The shape parameters. /// The start point. /// - /// Area with applied filter + /// Area with applied filter /// - /// - /// filter - null - /// or - /// shape - null - /// + /// filter - null + /// or + /// shape - null Bitmap FilterImageArea(Bitmap image, int? width, int? height, @@ -371,7 +369,7 @@ Bitmap CutBitmap(Bitmap image, int width, int height, MaskShape shape, object sh Bitmap SetPixel(Bitmap image, Point point, Color color, int radius); /// - /// Fills the area with color. + /// Fills the area with color. /// /// The image. /// The width. @@ -381,13 +379,11 @@ Bitmap CutBitmap(Bitmap image, int width, int height, MaskShape shape, object sh /// The shape parameters. /// The optional starting point (top-left corner) of the rectangle. Defaults to (0, 0). /// - /// Generates a filter for a certain area + /// Generates a filter for a certain area /// - /// - /// filter - null - /// or - /// shape - null - /// + /// filter - null + /// or + /// shape - null Bitmap FillAreaWithColor( Bitmap image, int? width, @@ -574,4 +570,4 @@ Bitmap FillAreaWithColor( /// Image as string string BitmapImageToBase64(BitmapImage bitmapImage); } -} +} \ No newline at end of file diff --git a/Imaging/ITextureGenerator.cs b/Imaging/ITextureGenerator.cs index b0c4a084..6ded0917 100644 --- a/Imaging/ITextureGenerator.cs +++ b/Imaging/ITextureGenerator.cs @@ -99,7 +99,7 @@ Bitmap GenerateCanvasBitmap( int height); /// - /// Generates the texture. + /// Generates the texture. /// /// The width. /// The height. @@ -108,13 +108,11 @@ Bitmap GenerateCanvasBitmap( /// The Start point. /// The shape parameters. /// - /// Texture Bitmap + /// Texture Bitmap /// - /// - /// filter - null - /// or - /// shape - null - /// + /// filter - null + /// or + /// shape - null Bitmap GenerateTexture( int width, int height, @@ -124,7 +122,7 @@ Bitmap GenerateTexture( object shapeParams = null); /// - /// Generates the texture overlay. + /// Generates the texture overlay. /// /// The image. /// The width. @@ -134,15 +132,13 @@ Bitmap GenerateTexture( /// The start point. /// The shape parameters. /// - /// Texture Bitmap + /// Texture Bitmap /// - /// - /// filter - null - /// or - /// shape - null - /// + /// filter - null + /// or + /// shape - null Bitmap GenerateTextureOverlay(Bitmap image, int width, int height, TextureType filter, MaskShape shape, Point? startPoint = null, object shapeParams = null); } -} +} \ No newline at end of file diff --git a/Imaging/ImageConverter.cs b/Imaging/ImageConverter.cs index 83970e0c..472d0f23 100644 --- a/Imaging/ImageConverter.cs +++ b/Imaging/ImageConverter.cs @@ -50,4 +50,4 @@ internal static string BitmapImageToBase64(BitmapImage bitmapImage) return Convert.ToBase64String(imageBytes); } } -} +} \ No newline at end of file diff --git a/Imaging/ImageExtension.cs b/Imaging/ImageExtension.cs index 72835ff4..b9235c08 100644 --- a/Imaging/ImageExtension.cs +++ b/Imaging/ImageExtension.cs @@ -48,4 +48,4 @@ public static BitmapImage ToBitmapImage(this Image image) return bitmap.ToBitmapImage(); } } -} +} \ No newline at end of file diff --git a/Imaging/ImageGif.cs b/Imaging/ImageGif.cs index ef9fe2ea..36e0467f 100644 --- a/Imaging/ImageGif.cs +++ b/Imaging/ImageGif.cs @@ -126,9 +126,7 @@ private async Task InitializeAsync() // Check if the image exists if (!File.Exists(GifSource)) // Log or show an error message - { return; - } try { @@ -136,10 +134,7 @@ private async Task InitializeAsync() var info = ImageGifMetadataExtractor.ExtractGifMetadata(GifSource); // Handle possible error if GIF is not animated - if (info.Frames.Count == 0) - { - return; - } + if (info.Frames.Count == 0) return; // Load the GIF frames using the handler _imageList = await ImageGifHandler.LoadGif(GifSource); @@ -179,10 +174,7 @@ private async Task InitializeAsync() ImageLoaded?.Invoke(this, EventArgs.Empty); // Optionally start the animation automatically if AutoStart is true - if (AutoStart) - { - StartAnimation(); - } + if (AutoStart) StartAnimation(); } catch (Exception ex) { @@ -196,13 +188,9 @@ private async Task InitializeAsync() private static void VisibilityPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { if ((Visibility)e.NewValue == Visibility.Visible) - { ((ImageGif)sender).StartAnimation(); - } else - { ((ImageGif)sender).StopAnimation(); - } } /// @@ -210,16 +198,11 @@ private static void VisibilityPropertyChanged(DependencyObject sender, Dependenc /// private static void ChangingFrameIndex(DependencyObject obj, DependencyPropertyChangedEventArgs ev) { - if (obj is not ImageGif { AutoStart: true } gifImage) - { - return; - } + if (obj is not ImageGif { AutoStart: true } gifImage) return; var newIndex = (int)ev.NewValue; if (newIndex >= 0 && newIndex < gifImage._imageList.Count) - { gifImage.Source = gifImage._imageList[newIndex]; - } } /// @@ -271,10 +254,7 @@ public void StopAnimation() /// if set to true [disposing]. private void Dispose(bool disposing) { - if (_isDisposed) - { - return; - } + if (_isDisposed) return; if (disposing) { @@ -295,4 +275,4 @@ private void Dispose(bool disposing) Dispose(false); } } -} +} \ No newline at end of file diff --git a/Imaging/ImageGifHandler.cs b/Imaging/ImageGifHandler.cs index 43c2dc08..8eecaf8e 100644 --- a/Imaging/ImageGifHandler.cs +++ b/Imaging/ImageGifHandler.cs @@ -154,10 +154,7 @@ internal static void CreateGif(string path, string target) //collect and convert all images var btm = lst.ConvertAll(ImageStream.GetOriginalBitmap); - if (btm.IsNullOrEmpty()) - { - return; - } + if (btm.IsNullOrEmpty()) return; GifCreator(btm, target); } @@ -172,10 +169,7 @@ internal static void CreateGif(List path, string target) //collect and convert all images var btm = path.ConvertAll(ImageStream.GetOriginalBitmap); - if (btm.IsNullOrEmpty()) - { - return; - } + if (btm.IsNullOrEmpty()) return; GifCreator(btm, target); } @@ -187,10 +181,7 @@ internal static void CreateGif(List path, string target) /// The target. internal static void CreateGif(IEnumerable frames, string target) { - if (frames == null) - { - return; - } + if (frames == null) return; GifCreator(frames, target); } @@ -210,9 +201,7 @@ private static void GifCreator(IEnumerable btm, string target) IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()))) - { gEnc.Frames.Add(BitmapFrame.Create(src)); - } using var ms = new MemoryStream(); gEnc.Save(ms); @@ -263,4 +252,4 @@ private static void GifCreator(IEnumerable frames, string target) gEnc.Save(fs); } } -} +} \ No newline at end of file diff --git a/Imaging/ImageGifInfo.cs b/Imaging/ImageGifInfo.cs index 6d1f5593..ef7de49e 100644 --- a/Imaging/ImageGifInfo.cs +++ b/Imaging/ImageGifInfo.cs @@ -156,4 +156,4 @@ public sealed class FrameInfo /// public Bitmap Image { get; set; } // Image of the frame } -} +} \ No newline at end of file diff --git a/Imaging/ImageGifMetadataExtractor.cs b/Imaging/ImageGifMetadataExtractor.cs index 0fd4ceed..d8b3b569 100644 --- a/Imaging/ImageGifMetadataExtractor.cs +++ b/Imaging/ImageGifMetadataExtractor.cs @@ -26,11 +26,13 @@ internal static class ImageGifMetadataExtractor internal static ImageGifInfo ExtractGifMetadata(string filePath) { if (!File.Exists(filePath)) - { throw new FileNotFoundException(ImagingResources.FileNotFoundMessage, filePath); - } - var metadata = new ImageGifInfo { Name = Path.GetFileName(filePath), Size = new FileInfo(filePath).Length }; + var metadata = new ImageGifInfo + { + Name = Path.GetFileName(filePath), + Size = new FileInfo(filePath).Length + }; double lastFrameDelay = 0; @@ -40,9 +42,7 @@ internal static ImageGifInfo ExtractGifMetadata(string filePath) // Read GIF Header metadata.Header = new string(reader.ReadChars(ImagingResources.GifHeaderLength)); if (!metadata.Header.StartsWith(ImagingResources.GifHeaderStart, StringComparison.Ordinal)) - { throw new InvalidDataException(ImagingResources.InvalidGifMessage); - } // Logical Screen Descriptor metadata.Width = reader.ReadInt16(); @@ -58,9 +58,7 @@ internal static ImageGifInfo ExtractGifMetadata(string filePath) : 0; if (metadata.HasGlobalColorTable) - { reader.BaseStream.Seek(metadata.GlobalColorTableSize, SeekOrigin.Current); - } while (reader.BaseStream.Position < reader.BaseStream.Length) { @@ -130,7 +128,8 @@ internal static ImageGifInfo ExtractGifMetadata(string filePath) case ImagingResources.ImageDescriptorId: metadata.Frames.Add(new FrameInfo { - Description = ImagingResources.ImageFrameDescription, DelayTime = lastFrameDelay + Description = ImagingResources.ImageFrameDescription, + DelayTime = lastFrameDelay }); reader.BaseStream.Seek(ImagingResources.ImageDescriptorLength, SeekOrigin.Current); @@ -144,10 +143,7 @@ internal static ImageGifInfo ExtractGifMetadata(string filePath) while (true) { var subBlockSize = reader.ReadByte(); - if (subBlockSize == ImagingResources.TerminatorBlockId) - { - break; - } + if (subBlockSize == ImagingResources.TerminatorBlockId) break; reader.BaseStream.Seek(subBlockSize, SeekOrigin.Current); } @@ -180,10 +176,7 @@ private static void SkipUnknownBlock(BinaryReader reader, byte blockId) while (true) { var subBlockSize = reader.ReadByte(); - if (subBlockSize == ImagingResources.TerminatorBlockId) - { - break; - } + if (subBlockSize == ImagingResources.TerminatorBlockId) break; reader.BaseStream.Seek(subBlockSize, SeekOrigin.Current); } @@ -199,13 +192,11 @@ private static void SkipExtensionBlocks(BinaryReader reader) { var blockSize = reader.ReadByte(); if (blockSize == ImagingResources.TerminatorBlockId) - { break; - } Console.WriteLine(ImagingResources.SkipExtensionBlockMessage, blockSize); reader.BaseStream.Seek(blockSize, SeekOrigin.Current); } } } -} +} \ No newline at end of file diff --git a/Imaging/ImageHelper.cs b/Imaging/ImageHelper.cs index 9c479388..85331c22 100644 --- a/Imaging/ImageHelper.cs +++ b/Imaging/ImageHelper.cs @@ -41,12 +41,10 @@ internal static List GetCirclePoints(Point center, int radius, int length for (var x = Math.Max(0, center.X - radius); x <= Math.Min(width - 1, center.X + radius); x++) { var dx = x - center.X; - var height = (int)Math.Sqrt((radius * radius) - (dx * dx)); + var height = (int)Math.Sqrt(radius * radius - dx * dx); for (var y = Math.Max(0, center.Y - height); y <= Math.Min(length - 1, center.Y + height); y++) - { points.Add(new Point(x, y)); - } } return points; @@ -76,9 +74,7 @@ internal static List GetCirclePoints(Point center, int radius, int length // Normalize the kernel for (var y = 0; y < size; y++) for (var x = 0; x < size; x++) - { kernel[y, x] /= sum; - } return kernel; } @@ -125,31 +121,16 @@ internal static Rectangle GetNonTransparentBounds(Bitmap image) for (var x = 0; x < image.Width; x++) { var pixel = image.GetPixel(x, y); - if (pixel.A == 0) - { - continue; - } + if (pixel.A == 0) continue; hasNonTransparentPixel = true; - if (x < minX) - { - minX = x; - } - - if (x > maxX) - { - maxX = x; - } - - if (y < minY) - { - minY = y; - } - - if (y > maxY) - { - maxY = y; - } + if (x < minX) minX = x; + + if (x > maxX) maxX = x; + + if (y < minY) minY = y; + + if (y > maxY) maxY = y; } // If all pixels are transparent, return a zero-sized rectangle @@ -167,9 +148,7 @@ internal static Rectangle GetNonTransparentBounds(Bitmap image) internal static void HandleException(Exception ex) { if (ex == null) - { throw new ArgumentNullException(nameof(ex), ImagingResources.ExceptionNull); - } // Log the exception details (implementation may vary) Trace.WriteLine(string.Format(ImagingResources.ExceptionType, ex.GetType().Name)); @@ -179,9 +158,7 @@ internal static void HandleException(Exception ex) // Optionally, rethrow or handle further if (ex is ArgumentException or InvalidOperationException or NotSupportedException or UriFormatException or IOException) - { throw new ApplicationException(ImagingResources.GeneralProcessingError, ex); - } } @@ -194,10 +171,7 @@ internal static void HandleException(Exception ex) [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ValidateImage(string method, Bitmap image) { - if (image != null) - { - return; - } + if (image != null) return; var innerException = new ArgumentNullException(string.Concat(method, ImagingResources.Spacing, nameof(image))); @@ -213,10 +187,7 @@ internal static void ValidateImage(string method, Bitmap image) [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ValidateImage(string method, BitmapImage image) { - if (image != null) - { - return; - } + if (image != null) return; var innerException = new ArgumentNullException(string.Concat(method, ImagingResources.Spacing, nameof(image))); @@ -248,10 +219,7 @@ private static (List Pixels, Color? Mean) ProcessPixels(DirectBitmap dbmB count++; } - if (!calculateMeanColor || count <= 0) - { - return (pixels, null); - } + if (!calculateMeanColor || count <= 0) return (pixels, null); var averageRed = rSum / count; var averageGreen = gSum / count; @@ -271,7 +239,7 @@ private static (List Pixels, Color? Mean) ProcessPixels(DirectBitmap dbmB [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static double Interpolate(double a, double b, double t) { - return (a * (1 - t)) + (b * t); + return a * (1 - t) + b * t; } /// @@ -319,15 +287,10 @@ internal static void ValidateFilePath(string path) internal static void ValidateParameters(int minValue, int maxValue, int alpha) { if (minValue is < 0 or > 255 || maxValue is < 0 or > 255 || minValue > maxValue) - { throw new ArgumentException( ImagingResources.ErrorColorRange); - } - if (alpha is < 0 or > 255) - { - throw new ArgumentException(ImagingResources.ErrorColorRange); - } + if (alpha is < 0 or > 255) throw new ArgumentException(ImagingResources.ErrorColorRange); } } -} +} \ No newline at end of file diff --git a/Imaging/ImageMask.cs b/Imaging/ImageMask.cs index 7cd854a4..f0414687 100644 --- a/Imaging/ImageMask.cs +++ b/Imaging/ImageMask.cs @@ -81,4 +81,4 @@ internal static Bitmap ApplyPolygonMask(Image bitmap, Point[] points) return polyBitmap; } } -} +} \ No newline at end of file diff --git a/Imaging/ImageOverlays.cs b/Imaging/ImageOverlays.cs index 2633f906..8e13fdb6 100644 --- a/Imaging/ImageOverlays.cs +++ b/Imaging/ImageOverlays.cs @@ -98,9 +98,9 @@ public static Bitmap CrossFadeImages(Image imgOne, Image imgTwo, float factor) { return ProcessImages(imgOne, imgTwo, (color1, color2) => { - var r = ImageHelper.Clamp((int)((color1.R * (1 - factor)) + (color2.R * factor))); - var g = ImageHelper.Clamp((int)((color1.G * (1 - factor)) + (color2.G * factor))); - var b = ImageHelper.Clamp((int)((color1.B * (1 - factor)) + (color2.B * factor))); + var r = ImageHelper.Clamp((int)(color1.R * (1 - factor) + color2.R * factor)); + var g = ImageHelper.Clamp((int)(color1.G * (1 - factor) + color2.G * factor)); + var b = ImageHelper.Clamp((int)(color1.B * (1 - factor) + color2.B * factor)); return Color.FromArgb(r, g, b); }); } @@ -149,9 +149,9 @@ public static Bitmap AmplitudeImages(Image imgOne, Image imgTwo) { return ProcessImages(imgOne, imgTwo, (color1, color2) => { - var r = (int)Math.Sqrt((color1.R * color1.R) + (color2.R * color2.R)); - var g = (int)Math.Sqrt((color1.G * color1.G) + (color2.G * color2.G)); - var b = (int)Math.Sqrt((color1.B * color1.B) + (color2.B * color2.B)); + var r = (int)Math.Sqrt(color1.R * color1.R + color2.R * color2.R); + var g = (int)Math.Sqrt(color1.G * color1.G + color2.G * color2.G); + var b = (int)Math.Sqrt(color1.B * color1.B + color2.B * color2.B); return Color.FromArgb(ImageHelper.Clamp(r), ImageHelper.Clamp(g), ImageHelper.Clamp(b)); }); } @@ -166,9 +166,7 @@ public static Bitmap AmplitudeImages(Image imgOne, Image imgTwo) private static Bitmap ProcessImages(Image imgOne, Image imgTwo, Func pixelOperation) { if (imgOne.Width != imgTwo.Width || imgOne.Height != imgTwo.Height) - { throw new ArgumentException("All images must have the same dimensions."); - } var width = imgOne.Width; var height = imgOne.Height; @@ -204,4 +202,4 @@ private static Bitmap ProcessImages(Image imgOne, Image imgTwo, Func { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } }, - { FiltersType.BoxBlur, new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } }, { - FiltersType.MotionBlur, new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } + FiltersType.BoxBlur, + new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } + }, + { + FiltersType.MotionBlur, + new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } + }, + { + FiltersType.Sharpen, + new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } + }, + { + FiltersType.Emboss, + new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } + }, + { + FiltersType.Laplacian, + new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } }, - { FiltersType.Sharpen, new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } }, - { FiltersType.Emboss, new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } }, - { FiltersType.Laplacian, new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } }, { FiltersType.EdgeEnhance, new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } @@ -417,12 +430,16 @@ static ImageRegister() TextureSetting[TextureType.Concrete] = new TextureConfiguration { - MinValue = 50, MaxValue = 200, TurbulenceSize = 16 + MinValue = 50, + MaxValue = 200, + TurbulenceSize = 16 }; TextureSetting[TextureType.Canvas] = new TextureConfiguration { - LineSpacing = 8, LineColor = Color.FromArgb(210, 180, 140), LineThickness = 1 + LineSpacing = 8, + LineColor = Color.FromArgb(210, 180, 140), + LineThickness = 1 }; // Add more default settings as needed @@ -563,12 +580,8 @@ public void LoadSettingsFromJson(string json) var settings = JsonSerializer.Deserialize>>(json); if (settings != null) - { foreach (var (imageFilters, filter) in settings) - { _filterPropertyMap[imageFilters] = filter; - } - } } catch (Exception ex) when (ex is ArgumentNullException or JsonException or NotSupportedException) { @@ -585,4 +598,4 @@ public string GetSettingsAsJson() return JsonSerializer.Serialize(_filterPropertyMap, new JsonSerializerOptions { WriteIndented = true }); } } -} +} \ No newline at end of file diff --git a/Imaging/ImageRender.cs b/Imaging/ImageRender.cs index e27517b5..b597d401 100644 --- a/Imaging/ImageRender.cs +++ b/Imaging/ImageRender.cs @@ -132,7 +132,7 @@ public Bitmap FilterImage(Bitmap image, FiltersType filter) /// /// - /// Filters the image area. + /// Filters the image area. /// /// The image. /// The width. @@ -142,13 +142,11 @@ public Bitmap FilterImage(Bitmap image, FiltersType filter) /// The shape parameters. /// The start point. /// - /// Area with applied filter + /// Area with applied filter /// - /// - /// filter - null - /// or - /// shape - null - /// + /// filter - null + /// or + /// shape - null public Bitmap FilterImageArea(Bitmap image, int? width, int? height, @@ -524,7 +522,7 @@ public Bitmap SetPixel(Bitmap image, Point point, Color color, int radius) /// /// - /// Fills the color of the area with. + /// Fills the color of the area with. /// /// The image. /// The width. @@ -536,11 +534,9 @@ public Bitmap SetPixel(Bitmap image, Point point, Color color, int radius) /// /// The Changed Image /// - /// - /// filter - null - /// or - /// shape - null - /// + /// filter - null + /// or + /// shape - null public Bitmap FillAreaWithColor( Bitmap image, int? width, @@ -852,4 +848,4 @@ public string BitmapImageToBase64(BitmapImage bitmapImage) return ImageConverter.BitmapImageToBase64(bitmapImage); } } -} +} \ No newline at end of file diff --git a/Imaging/ImageStream.cs b/Imaging/ImageStream.cs index 3bc98598..9154c71c 100644 --- a/Imaging/ImageStream.cs +++ b/Imaging/ImageStream.cs @@ -243,16 +243,11 @@ internal static Bitmap CombineBitmap(List files) { //go through each image and draw it on the final image foreach (var image in images) - { graph.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height)); - } } - foreach (var image in images) - { - image.Dispose(); - } + foreach (var image in images) image.Dispose(); //before return please Convert return btm; @@ -384,10 +379,7 @@ internal static Bitmap RotateImage(Bitmap image, int degree) ImageHelper.ValidateImage(nameof(RotateImage), image); //no need to do anything - if (degree is 360 or 0) - { - return image; - } + if (degree is 360 or 0) return image; if (degree is > 360 or < -360) { @@ -408,8 +400,8 @@ internal static Bitmap RotateImage(Bitmap image, int degree) var point = corners[i]; corners[i] = new PointF( - (float)((point.X * ExtendedMath.CalcCos(degree)) - (point.Y * ExtendedMath.CalcSin(degree))), - (float)((point.X * ExtendedMath.CalcSin(degree)) + (point.Y * ExtendedMath.CalcCos(degree)))); + (float)(point.X * ExtendedMath.CalcCos(degree) - point.Y * ExtendedMath.CalcSin(degree)), + (float)(point.X * ExtendedMath.CalcSin(degree) + point.Y * ExtendedMath.CalcCos(degree))); } // Find the min and max x and y coordinates. @@ -453,18 +445,13 @@ internal static Bitmap RotateImage(Bitmap image, int degree) /// internal static Bitmap CropImage(Bitmap image) { - if (image == null) - { - throw new ArgumentNullException(nameof(image)); - } + if (image == null) throw new ArgumentNullException(nameof(image)); var bounds = ImageHelper.GetNonTransparentBounds(image); if (bounds.Width <= 0 || bounds.Height <= 0) // Return an empty image or handle this case as needed - { return new Bitmap(1, 1); - } var croppedBitmap = new Bitmap(bounds.Width, bounds.Height); using var graphics = Graphics.FromImage(croppedBitmap); @@ -509,10 +496,7 @@ internal static void SaveBitmap(Bitmap image, string path, ImageFormat format) var fileNameOnly = Path.GetFileNameWithoutExtension(path); var extension = Path.GetExtension(path); var directory = Path.GetDirectoryName(path); - if (!Directory.Exists(directory)) - { - return; - } + if (!Directory.Exists(directory)) return; var newPath = path; @@ -560,10 +544,7 @@ internal static Bitmap ConvertWhiteToTransparent(Bitmap image, int threshold) var color = result.GetPixel(x, y); //not in the area? continue, 255 is White - if (255 - color.R >= threshold || 255 - color.G >= threshold || 255 - color.B >= threshold) - { - continue; - } + if (255 - color.R >= threshold || 255 - color.G >= threshold || 255 - color.B >= threshold) continue; //replace Value under the threshold with pure White pixelsToSet.Add((x, y, replacementColor)); @@ -603,9 +584,7 @@ internal static Color GetPixel(Bitmap image, Point point) ImageHelper.ValidateImage(nameof(GetPixel), image); if (point.X < 0 || point.X >= image.Width || point.Y < 0 || point.Y >= image.Height) - { throw new ArgumentOutOfRangeException(nameof(point), ImagingResources.ErrorOutOfBounds); - } //use our new Format var dbm = DirectBitmap.GetInstance(image); @@ -629,22 +608,14 @@ internal static Color GetPixel(Bitmap image, Point point, int radius) { ImageHelper.ValidateImage(nameof(GetPixel), image); - if (radius < 0) - { - throw new ArgumentOutOfRangeException(nameof(radius), ImagingResources.ErrorRadius); - } + if (radius < 0) throw new ArgumentOutOfRangeException(nameof(radius), ImagingResources.ErrorRadius); if (point.X < 0 || point.X >= image.Width || point.Y < 0 || point.Y >= image.Height) - { throw new ArgumentOutOfRangeException(nameof(point), ImagingResources.ErrorOutOfBounds); - } var points = ImageHelper.GetCirclePoints(point, radius, image.Height, image.Width); - if (points.Count == 0) - { - return GetPixel(image, point); - } + if (points.Count == 0) return GetPixel(image, point); int redSum = 0, greenSum = 0, blueSum = 0; @@ -729,7 +700,7 @@ internal static Bitmap SetPixel(Bitmap image, Point point, Color color, int radi } /// - /// Fills the area with color. + /// Fills the area with color. /// /// The image. /// The width. @@ -739,13 +710,11 @@ internal static Bitmap SetPixel(Bitmap image, Point point, Color color, int radi /// The shape parameters. /// The optional starting point (top-left corner) of the rectangle. Defaults to (0, 0). /// - /// Generates a filter for a certain area + /// Generates a filter for a certain area /// - /// - /// filter - null - /// or - /// shape - null - /// + /// filter - null + /// or + /// shape - null internal static Bitmap FillAreaWithColor( Bitmap image, int? width, @@ -756,10 +725,7 @@ internal static Bitmap FillAreaWithColor( Point? startPoint = null) { // Validate input - if (image == null) - { - throw new ArgumentNullException(nameof(image)); - } + if (image == null) throw new ArgumentNullException(nameof(image)); // Default start point var actualStartPoint = startPoint ?? new Point(0, 0); @@ -816,10 +782,7 @@ internal static Bitmap FloodFillScanLineStack(Bitmap image, int x, int y, Color var result = new DirectBitmap(image); var oldColor = dbm.GetPixel(x, y); - if (oldColor == newColor) - { - return image; // Return original image if the color is the same - } + if (oldColor == newColor) return image; // Return original image if the color is the same var pixelData = new List<(int x, int y, Color color)>(); @@ -832,10 +795,7 @@ internal static Bitmap FloodFillScanLineStack(Bitmap image, int x, int y, Color var x1 = x; // Move to the left boundary - while (x1 >= 0 && dbm.GetPixel(x1, y) == oldColor) - { - x1--; - } + while (x1 >= 0 && dbm.GetPixel(x1, y) == oldColor) x1--; x1++; bool spanBelow; @@ -914,9 +874,9 @@ internal static Bitmap AdjustColor(Bitmap image, Color sourceColor, Color target private static ColorMatrix CreateColorMatrix(Color sourceColor, Color targetColor) { // Calculate the difference between source and target colors for each channel - var rRatio = (targetColor.R / 255f) - (sourceColor.R / 255f); - var gRatio = (targetColor.G / 255f) - (sourceColor.G / 255f); - var bRatio = (targetColor.B / 255f) - (sourceColor.B / 255f); + var rRatio = targetColor.R / 255f - sourceColor.R / 255f; + var gRatio = targetColor.G / 255f - sourceColor.G / 255f; + var bRatio = targetColor.B / 255f - sourceColor.B / 255f; return new ColorMatrix(new[] { @@ -928,4 +888,4 @@ private static ColorMatrix CreateColorMatrix(Color sourceColor, Color targetColo }); } } -} +} \ No newline at end of file diff --git a/Imaging/ImageStreamHsv.cs b/Imaging/ImageStreamHsv.cs index 92e5094a..bc41351e 100644 --- a/Imaging/ImageStreamHsv.cs +++ b/Imaging/ImageStreamHsv.cs @@ -66,10 +66,7 @@ internal static Bitmap AdjustBrightness(Bitmap image, double brightnessFactor) /// gamma - Gamma must be greater than 0. internal static Bitmap ApplyGammaCorrection(Bitmap image, double gamma) { - if (gamma <= 0) - { - throw new ArgumentOutOfRangeException(nameof(gamma), "Gamma must be greater than 0."); - } + if (gamma <= 0) throw new ArgumentOutOfRangeException(nameof(gamma), "Gamma must be greater than 0."); var gammaCorrection = 1.0 / gamma; return ProcessImage(image, colorHsv => @@ -130,4 +127,4 @@ private static Bitmap ApplyPixelChanges(DirectBitmap result, List<(int x, int y, } } } -} +} \ No newline at end of file diff --git a/Imaging/ImageStreamMedia.cs b/Imaging/ImageStreamMedia.cs index db9d9e5c..99a39da9 100644 --- a/Imaging/ImageStreamMedia.cs +++ b/Imaging/ImageStreamMedia.cs @@ -165,4 +165,4 @@ internal static BitmapImage BitmapToBitmapImage(Bitmap image) return bitmapImage; } } -} +} \ No newline at end of file diff --git a/Imaging/ImagingResources.cs b/Imaging/ImagingResources.cs index 3948f65e..948e66ba 100644 --- a/Imaging/ImagingResources.cs +++ b/Imaging/ImagingResources.cs @@ -299,37 +299,37 @@ public static class ImagingResources internal const string ErrorLoadSettings = "Error loading Configuration:"; /// - /// The error with shape polygon (const). Value: "Error loading Configuration:" + /// The error with shape polygon (const). Value: "Error loading Configuration:" /// internal const string ErrorWithShapePolygon = "Error loading Configuration:"; /// - /// The invalid dimensions (const). Value: "Width and height must be positive integers." + /// The invalid dimensions (const). Value: "Width and height must be positive integers." /// public const string InvalidDimensions = "Width and height must be positive integers."; /// - /// The image settings null (const). Value: "Image settings cannot be null." + /// The image settings null (const). Value: "Image settings cannot be null." /// public const string ImageSettingsNull = "Image settings cannot be null."; /// - /// The invalid texture settings (const). Value: "Invalid texture settings." + /// The invalid texture settings (const). Value: "Invalid texture settings." /// public const string InvalidTextureSettings = "Invalid texture settings."; /// - /// The unsupported texture (const). Value: "Unsupported texture type." + /// The unsupported texture (const). Value: "Unsupported texture type." /// public const string UnsupportedTexture = "Unsupported texture type."; /// - /// The invalid polygon parameters (const). Value:"Invalid shape parameters for polygon mask." + /// The invalid polygon parameters (const). Value:"Invalid shape parameters for polygon mask." /// public const string InvalidPolygonParams = "Invalid shape parameters for polygon mask."; /// - /// The unsupported shape (const). Value: "Unsupported shape type." + /// The unsupported shape (const). Value: "Unsupported shape type." /// public const string UnsupportedShape = "Unsupported shape type."; @@ -341,35 +341,34 @@ public static class ImagingResources "Error: minValue and maxValue must be between 0 and 255, and minValue must not be greater than maxValue."; /// - /// The exception null (const). Value: "The exception object cannot be null." + /// The exception null (const). Value: "The exception object cannot be null." /// public const string ExceptionNull = "The exception object cannot be null."; /// - /// The exception type (const). Value: "Exception Type: {0}" + /// The exception type (const). Value: "Exception Type: {0}" /// public const string ExceptionType = "Exception Type: {0}"; /// - /// The exception message (const). Value: "Message: {0}" + /// The exception message (const). Value: "Message: {0}" /// public const string ExceptionMessage = "Message: {0}"; /// - /// The exception stack trace (const). Value: "Stack Trace: {0}" + /// The exception stack trace (const). Value: "Stack Trace: {0}" /// public const string ExceptionStackTrace = "Stack Trace: {0}"; /// - /// The general processing error (const). Value: "An error occurred while processing the image." + /// The general processing error (const). Value: "An error occurred while processing the image." /// public const string GeneralProcessingError = "An error occurred while processing the image."; /// /// The File Appendix /// - public static readonly List Appendix = new() - { + public static readonly List Appendix = new() { JpgExt, PngExt, BmpExt, @@ -377,4 +376,4 @@ public static class ImagingResources TifExt }; } -} +} \ No newline at end of file diff --git a/Imaging/LayerSettings.cs b/Imaging/LayerSettings.cs index 0b1a756c..b12981aa 100644 --- a/Imaging/LayerSettings.cs +++ b/Imaging/LayerSettings.cs @@ -41,4 +41,4 @@ public LayerSettings(bool isVisible, float alpha) /// public string LayerName { get; internal set; } } -} +} \ No newline at end of file diff --git a/Imaging/Lif.cs b/Imaging/Lif.cs index de9b3316..ce8d0812 100644 --- a/Imaging/Lif.cs +++ b/Imaging/Lif.cs @@ -21,10 +21,7 @@ public Lif(List layers, List layerSettings) // Merge all visible layers to create the final image public Bitmap MergeLayers() { - if (Layers.Count == 0) - { - return null; - } + if (Layers.Count == 0) return null; // Start with base layer (always visible) var finalImage = Layers[0]; @@ -60,10 +57,10 @@ private void ApplyDelta(Cif baseImage, Cif deltaLayer, LayerSettings settings) private Color ApplyAlpha(Color baseColor, Color deltaColor, float alpha) { - var r = (int)((deltaColor.R * alpha) + (baseColor.R * (1 - alpha))); - var g = (int)((deltaColor.G * alpha) + (baseColor.G * (1 - alpha))); - var b = (int)((deltaColor.B * alpha) + (baseColor.B * (1 - alpha))); + var r = (int)(deltaColor.R * alpha + baseColor.R * (1 - alpha)); + var g = (int)(deltaColor.G * alpha + baseColor.G * (1 - alpha)); + var b = (int)(deltaColor.B * alpha + baseColor.B * (1 - alpha)); return Color.FromArgb(r, g, b); } } -} +} \ No newline at end of file diff --git a/Imaging/LifProcessing.cs b/Imaging/LifProcessing.cs index 21d92ec9..83114670 100644 --- a/Imaging/LifProcessing.cs +++ b/Imaging/LifProcessing.cs @@ -28,12 +28,8 @@ public static bool AreColorCountsSimilar(Dictionary colorCount1, Dic var similarPixels = 0; foreach (var color in colorCount1.Keys) - { if (colorCount2.ContainsKey(color)) - { similarPixels += Math.Min(colorCount1[color], colorCount2[color]); - } - } var similarity = (double)similarPixels / Math.Min(totalPixels1, totalPixels2); return similarity >= threshold; @@ -67,13 +63,10 @@ public static Dictionary> ConvertToCifFromBitmap(Bitmap bitmap) for (var x = 0; x < bitmap.Width; x++) { var pixelColor = bitmap.GetPixel(x, y); - var pixelIndex = (y * bitmap.Width) + x; + var pixelIndex = y * bitmap.Width + x; // Group pixels by color - if (!cif.ContainsKey(pixelColor)) - { - cif[pixelColor] = new List(); - } + if (!cif.ContainsKey(pixelColor)) cif[pixelColor] = new List(); cif[pixelColor].Add(pixelIndex); } @@ -106,31 +99,20 @@ public static Dictionary> CompressCif(Dictionary> cif2, double threshold) { if (!AreColorCountsSimilar(GetColorCount(cif1), GetColorCount(cif2), threshold)) - { return cif2; // No compression possible, return the second CIF as is - } var compressedCif = new Dictionary>(); // Store the base CIF data - foreach (var entry in cif1) - { - compressedCif[entry.Key] = new List(entry.Value); // Copy existing pixels - } + foreach (var entry in cif1) compressedCif[entry.Key] = new List(entry.Value); // Copy existing pixels // Apply delta logic for similar colors foreach (var entry in cif2) - { if (!compressedCif.ContainsKey(entry.Key)) - { compressedCif[entry.Key] = new List(); - } else // Only add new pixels if the color already exists - { compressedCif[entry.Key].AddRange(entry.Value); - } - } return compressedCif; } @@ -141,4 +123,4 @@ private static Dictionary GetColorCount(Dictionary> return cif.ToDictionary(entry => entry.Key, entry => entry.Value.Count); } } -} +} \ No newline at end of file diff --git a/Imaging/MaskShape.cs b/Imaging/MaskShape.cs index 43828348..02c6391b 100644 --- a/Imaging/MaskShape.cs +++ b/Imaging/MaskShape.cs @@ -30,4 +30,4 @@ public enum MaskShape /// Polygon } -} +} \ No newline at end of file diff --git a/Imaging/PixelData.cs b/Imaging/PixelData.cs index 13de3283..08fe4001 100644 --- a/Imaging/PixelData.cs +++ b/Imaging/PixelData.cs @@ -86,4 +86,4 @@ public PixelData(int x, int y, byte r, byte g, byte b, byte a = 255) A = a; } } -} +} \ No newline at end of file diff --git a/Imaging/TextureAreas.cs b/Imaging/TextureAreas.cs index 6de56795..ba65a429 100644 --- a/Imaging/TextureAreas.cs +++ b/Imaging/TextureAreas.cs @@ -38,14 +38,10 @@ internal static Bitmap GenerateTexture( Point? startPoint = null) { if (width <= 0 || height <= 0) - { throw new ArgumentException(ImagingResources.InvalidDimensions); - } if (imageSettings == null) - { throw new ArgumentNullException(nameof(imageSettings), ImagingResources.ImageSettingsNull); - } // Default start point var actualStartPoint = startPoint ?? new Point(0, 0); @@ -83,8 +79,7 @@ internal static Bitmap GenerateTexture( TextureType.Canvas => TextureStream.GenerateCanvasBitmap( width, height, settings.LineSpacing, settings.LineColor, settings.LineThickness, settings.Alpha), - _ => throw new ArgumentOutOfRangeException(nameof(texture), texture, - ImagingResources.UnsupportedTexture) + _ => throw new ArgumentOutOfRangeException(nameof(texture), texture, ImagingResources.UnsupportedTexture) }; // Validate shape parameters and apply mask diff --git a/Imaging/TextureConfiguration.cs b/Imaging/TextureConfiguration.cs index dae57995..55bee6fe 100644 --- a/Imaging/TextureConfiguration.cs +++ b/Imaging/TextureConfiguration.cs @@ -162,4 +162,4 @@ public sealed class TextureConfiguration /// public double Angle2 { get; init; } = 135.0; } -} +} \ No newline at end of file diff --git a/Imaging/TextureGenerator.cs b/Imaging/TextureGenerator.cs index 9a15fc6b..44dc5400 100644 --- a/Imaging/TextureGenerator.cs +++ b/Imaging/TextureGenerator.cs @@ -166,7 +166,7 @@ public Bitmap GenerateTexture(int width, int height, TextureType filter, MaskSha /// /// - /// Generates the texture overlay. + /// Generates the texture overlay. /// /// The image. /// The height. @@ -176,13 +176,11 @@ public Bitmap GenerateTexture(int width, int height, TextureType filter, MaskSha /// The shape parameters. /// The width. /// - /// Texture Bitmap + /// Texture Bitmap /// - /// - /// filter - null - /// or - /// shape - null - /// + /// filter - null + /// or + /// shape - null public Bitmap GenerateTextureOverlay(Bitmap image, int width, int height, TextureType filter, MaskShape shape, Point? startPoint = null, object shapeParams = null) @@ -262,4 +260,4 @@ public Bitmap GenerateCanvasBitmap(int width, int height) ); } } -} +} \ No newline at end of file diff --git a/Imaging/TextureStream.cs b/Imaging/TextureStream.cs index 6bc17cd6..3a7f74bd 100644 --- a/Imaging/TextureStream.cs +++ b/Imaging/TextureStream.cs @@ -75,17 +75,11 @@ internal static Bitmap GenerateNoiseBitmap( double value; if (useTurbulence) - { value = Turbulence(x, y, turbulenceSize); - } else if (useSmoothNoise) - { value = SmoothNoise(x, y); - } else - { value = Noise[y % NoiseHeight, x % NoiseWidth]; - } var colorValue = minValue + (int)((maxValue - minValue) * value); colorValue = Math.Max(minValue, Math.Min(maxValue, colorValue)); @@ -174,8 +168,8 @@ internal static Bitmap GenerateMarbleBitmap( for (var y = 0; y < height; y++) for (var x = 0; x < width; x++) { - var xyValue = (x * xPeriod / NoiseWidth) + (y * yPeriod / NoiseHeight) + - (turbulencePower * Turbulence(x, y, turbulenceSize) / 256.0); + var xyValue = x * xPeriod / NoiseWidth + y * yPeriod / NoiseHeight + + turbulencePower * Turbulence(x, y, turbulenceSize) / 256.0; var sineValue = 226 * Math.Abs(Math.Sin(xyValue * Math.PI)); var r = Math.Clamp(baseColor.R + (int)sineValue, 0, 255); var g = Math.Clamp(baseColor.G + (int)sineValue, 0, 255); @@ -224,10 +218,10 @@ internal static Bitmap GenerateWoodBitmap( for (var y = 0; y < height; y++) for (var x = 0; x < width; x++) { - var xValue = (x - (width / 2.0)) / width; - var yValue = (y - (height / 2.0)) / height; - var distValue = Math.Sqrt((xValue * xValue) + (yValue * yValue)) + - (turbulencePower * Turbulence(x, y, turbulenceSize) / 256.0); + var xValue = (x - width / 2.0) / width; + var yValue = (y - height / 2.0) / height; + var distValue = Math.Sqrt(xValue * xValue + yValue * yValue) + + turbulencePower * Turbulence(x, y, turbulenceSize) / 256.0; var sineValue = 128.0 * Math.Abs(Math.Sin(2 * xyPeriod * distValue * Math.PI)); var r = Math.Clamp(baseColor.R + (int)sineValue, 0, 255); @@ -275,9 +269,9 @@ internal static Bitmap GenerateWaveBitmap( for (var x = 0; x < width; x++) { var turbulenceValue = Turbulence(x, y, turbulenceSize); - var xValue = ((x - (width / 2.0)) / width) + (turbulencePower * turbulenceValue / 256.0); - var yValue = ((y - (height / 2.0)) / height) + - (turbulencePower * Turbulence(height - y, width - x, turbulenceSize) / 256.0); + var xValue = (x - width / 2.0) / width + turbulencePower * turbulenceValue / 256.0; + var yValue = (y - height / 2.0) / height + + turbulencePower * Turbulence(height - y, width - x, turbulenceSize) / 256.0; var sineValue = 22.0 * Math.Abs(Math.Sin(xyPeriod * xValue * Math.PI) + @@ -336,41 +330,33 @@ internal static Bitmap GenerateCrosshatchBitmap( // Draw first set of lines for (var y = 0; y < height; y += lineSpacing) - { graphics.DrawLine( pen, 0, y, - (int)((width * dx1) + (width * dy1)), - (int)((y * dx1) + (width * dy1))); - } + (int)(width * dx1 + width * dy1), + (int)(y * dx1 + width * dy1)); for (var x = 0; x < width; x += lineSpacing) - { graphics.DrawLine( pen, x, 0, - (int)((x * dx1) + (height * dx1)), - (int)((height * dx1) + (height * dy1))); - } + (int)(x * dx1 + height * dx1), + (int)(height * dx1 + height * dy1)); // Draw second set of lines for (var y = 0; y < height; y += lineSpacing) - { graphics.DrawLine( pen, 0, y, - (int)((width * dx2) + (height * dy2)), - (int)((y * dx2) + (height * dy2))); - } + (int)(width * dx2 + height * dy2), + (int)(y * dx2 + height * dy2)); for (var x = 0; x < width; x += lineSpacing) - { graphics.DrawLine( pen, x, 0, - (int)((x * dx2) + (width * dx2)), - (int)((width * dx2) + (height * dy2))); - } + (int)(x * dx2 + width * dx2), + (int)(width * dx2 + height * dy2)); return crosshatchBitmap; } @@ -445,21 +431,17 @@ internal static Bitmap GenerateCanvasBitmap( // Draw vertical fibers for (var x = 0; x < width; x += lineSpacing) - { using (var fiberBrush = new SolidBrush(Color.FromArgb(alpha, lineColor))) { g.FillRectangle(fiberBrush, x, 0, lineThickness, height); } - } // Draw horizontal fibers for (var y = 0; y < height; y += lineSpacing) - { using (var fiberBrush = new SolidBrush(Color.FromArgb(alpha, lineColor))) { g.FillRectangle(fiberBrush, 0, y, width, lineThickness); } - } } return canvasBitmap.Bitmap; @@ -474,9 +456,7 @@ private static void GenerateBaseNoise() var random = new Random(); for (var y = 0; y < NoiseHeight; y++) for (var x = 0; x < NoiseWidth; x++) - { Noise[y, x] = random.NextDouble(); // Random value between 0.0 and 1.0 - } } /// @@ -532,4 +512,4 @@ private static int RandomVariation(int min, int max) return rand.Next(min, max); } } -} +} \ No newline at end of file diff --git a/Imaging/TextureType.cs b/Imaging/TextureType.cs index f739a379..9daadb85 100644 --- a/Imaging/TextureType.cs +++ b/Imaging/TextureType.cs @@ -55,4 +55,4 @@ public enum TextureType /// Canvas } -} +} \ No newline at end of file diff --git a/Mathematics/ExtendedMath.cs b/Mathematics/ExtendedMath.cs index 6757a2d3..8d989f8e 100644 --- a/Mathematics/ExtendedMath.cs +++ b/Mathematics/ExtendedMath.cs @@ -24,7 +24,7 @@ public static class ExtendedMath /// https://de.wikipedia.org/wiki/Radiant_(Einheit) /// /// Degree we want to Rotate - /// The . + /// The The radial Value. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double CalcCos(int degree) { @@ -47,7 +47,7 @@ public static double CalcCos(int degree) /// https://de.wikipedia.org/wiki/Radiant_(Einheit) /// /// Degree we want to Rotate - /// The . + /// The The radial Value. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double CalcSin(int degree) { @@ -101,5 +101,29 @@ public static double CalcTan(int degree) const double rad = Math.PI / 180.0; return Math.Tan(normalizedDegree * rad); } + + /// + /// Calculates the cos as float. Variation of CalcCos. + /// + /// The degree. + /// The The radial Value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float CalcCosF(int degree) => (float)CalcCos(degree); + + /// + /// Calculates the sin float. Variation of CalcSin. + /// + /// The degree. + /// The The radial Value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float CalcSinF(int degree) => (float)CalcSin(degree); + + /// + /// Calculates the tan float. Variation of CalcTan. + /// + /// The degree. + /// The The radial Value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float CalcTanF(int degree) => (float)CalcTan(degree); } } diff --git a/RenderEngine/ImageProcessor.cs b/RenderEngine/ImageProcessor.cs index ac1e30d8..d6fb3641 100644 --- a/RenderEngine/ImageProcessor.cs +++ b/RenderEngine/ImageProcessor.cs @@ -36,5 +36,3 @@ // return processedBitmap; // } //} - - diff --git a/RenderEngine/RenderEngine.csproj b/RenderEngine/RenderEngine.csproj index 9bf3ac6c..3f16f70c 100644 --- a/RenderEngine/RenderEngine.csproj +++ b/RenderEngine/RenderEngine.csproj @@ -8,6 +8,7 @@ + diff --git a/RenderEngine/SkiaPixelControl.cs b/RenderEngine/SkiaPixelControl.cs new file mode 100644 index 00000000..db07287f --- /dev/null +++ b/RenderEngine/SkiaPixelControl.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Windows; +using SkiaSharp; +using SkiaSharp.Views.Desktop; +using SkiaSharp.Views.WPF; + +namespace RenderEngine +{ + public class SkiaPixelControl : SKElement + { + private SKBitmap _bitmap; + private System.Drawing.Bitmap _gdiBitmap; + private readonly List _dirtyRegions; + + static SkiaPixelControl() + { + // Default style for the control (if needed) + DefaultStyleKeyProperty.OverrideMetadata(typeof(SkiaPixelControl), new FrameworkPropertyMetadata(typeof(SkiaPixelControl))); + } + + public SkiaPixelControl() + { + _dirtyRegions = new List(); + } + + public void Initialize(int width, int height) + { + _bitmap = new SKBitmap(width, height); + _gdiBitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // Set to BGRA format for compatibility + using (var canvas = new SKCanvas(_bitmap)) + { + canvas.Clear(SKColors.Black); + } + } + + public void SetPixel(int x, int y, SKColor color) + { + if (_bitmap == null) + throw new InvalidOperationException("The control must be initialized before setting pixels."); + + _bitmap.SetPixel(x, y, color); + + // Mark the updated region as dirty (so that only relevant areas are repainted) + _dirtyRegions.Add(new SKRect(x, y, x + 1, y + 1)); + + // Trigger a repaint + InvalidateVisual(); + } + + public SKColor GetPixel(int x, int y) + { + if (_bitmap == null) + throw new InvalidOperationException("The control must be initialized before getting pixels."); + + return _bitmap.GetPixel(x, y); + } + + public void ChangeAreaOfPixels(int startX, int startY, int width, int height, byte[] pixelData) + { + if (_bitmap == null) + throw new InvalidOperationException("The control must be initialized before changing pixels."); + + // Update the pixels in the area defined by startX, startY, width, height + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + int srcIndex = (y * width + x) * 4; // BGRA32 format + int dstIndex = ((startY + y) * _bitmap.Width + (startX + x)) * 4; + + var color = new SKColor( + pixelData[srcIndex + 2], // Red + pixelData[srcIndex + 1], // Green + pixelData[srcIndex], // Blue + pixelData[srcIndex + 3] // Alpha + ); + + _bitmap.SetPixel(startX + x, startY + y, color); + } + } + + // Mark the updated area as dirty + _dirtyRegions.Add(new SKRect(startX, startY, startX + width, startY + height)); + + // Trigger a repaint + InvalidateVisual(); + } + + public System.Drawing.Bitmap GetGdiBitmap() + { + // Convert SkiaSharp Bitmap to System.Drawing Bitmap (BGRA to ARGB conversion) + for (int y = 0; y < _bitmap.Height; y++) + { + for (int x = 0; x < _bitmap.Width; x++) + { + var color = _bitmap.GetPixel(x, y); + _gdiBitmap.SetPixel(x, y, System.Drawing.Color.FromArgb(color.Alpha, color.Red, color.Green, color.Blue)); + } + } + + return _gdiBitmap; + } + + protected override void OnPaintSurface(SKPaintSurfaceEventArgs e) + { + base.OnPaintSurface(e); + + if (_bitmap == null) + return; + + var canvas = e.Surface.Canvas; + + // Clear the canvas + canvas.Clear(SKColors.Black); + + // Draw the bitmap with dirty region optimizations + foreach (var region in _dirtyRegions) + { + canvas.Save(); + + // Calculate the scaling factors to fit the control + float scaleX = (float)e.Info.Width / _bitmap.Width; + float scaleY = (float)e.Info.Height / _bitmap.Height; + + // Scale the canvas + canvas.Scale(scaleX, scaleY); + + // Transform the dirty region to the bitmap's coordinate space + var scaledRegion = new SKRect( + region.Left / scaleX, + region.Top / scaleY, + region.Right / scaleX, + region.Bottom / scaleY + ); + + // Clip to the scaled dirty region + canvas.ClipRect(region); + + // Draw only the affected region of the bitmap + canvas.DrawBitmap(_bitmap, scaledRegion, region); + + canvas.Restore(); + } + + + // Clear the dirty regions after drawing + _dirtyRegions.Clear(); + } + } +} diff --git a/RenderEngine/Tester.cs b/RenderEngine/Tester.cs deleted file mode 100644 index b5bcc8c5..00000000 --- a/RenderEngine/Tester.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System.Windows; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using SkiaSharp; -using SkiaSharp.Views.WPF; - -namespace RenderEngine -{ - public static class Tester - { - public static WriteableBitmap ProcessWithSkiaSharp(string imagePath) - { - // Load the image using SkiaSharp - using var bitmap = SKBitmap.Decode(imagePath); - // Access the raw pixel data as a byte array (ARGB format) - var pixelData = bitmap.Bytes; - - // Loop through the pixels and apply the grayscale conversion - for (var i = 0; i < pixelData.Length; i += 4) // Skip 4 bytes per pixel (ARGB) - { - var blue = pixelData[i]; - var green = pixelData[i + 1]; - var red = pixelData[i + 2]; - - // Calculate grayscale value (luminosity formula) - var grayValue = (byte)((red * 0.3) + (green * 0.59) + (blue * 0.11)); - - // Set new grayscale value for all channels - pixelData[i] = grayValue; // Blue channel - pixelData[i + 1] = grayValue; // Green channel - pixelData[i + 2] = grayValue; // Red channel - // Alpha channel remains unchanged - } - - // Create a WriteableBitmap from the processed pixel data - var writeableBitmap = new WriteableBitmap(bitmap.Width, bitmap.Height, 96, 96, PixelFormats.Bgra32, null); - - // Write the pixel data to the WriteableBitmap - writeableBitmap.WritePixels(new Int32Rect(0, 0, bitmap.Width, bitmap.Height), pixelData, bitmap.Width * 4, - 0); - - return writeableBitmap; - } - - public static WriteableBitmap Render() - { - // Create a bitmap - var bitmap = new SKBitmap(800, 600); - - // Create a canvas to draw on the bitmap - var canvas = new SKCanvas(bitmap); - - // Draw something or manipulate the bitmap - canvas.Clear(SKColors.White); - - // Convert to .NET Bitmap - return bitmap.ToWriteableBitmap(); - } - } -}