From f7d0e59d932235b3b94cb879fb37f5b7e0432100 Mon Sep 17 00:00:00 2001 From: Wayfarer Date: Wed, 1 Jan 2025 17:57:10 +0100 Subject: [PATCH] format --- 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 | 24 +-- 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 | 76 +++++++-- 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 +- RenderEngine/ImageProcessor.cs | 2 + RenderEngine/Tester.cs | 30 ++-- 83 files changed, 1276 insertions(+), 481 deletions(-) diff --git a/CommonControls/AssemblyInfo.cs b/CommonControls/AssemblyInfo.cs index 4a05c7d4..b9d746b1 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 8e6b8396..367b45f1 100644 --- a/CommonControls/ColorPicker.xaml.cs +++ b/CommonControls/ColorPicker.xaml.cs @@ -176,7 +176,10 @@ 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; @@ -197,7 +200,10 @@ 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; @@ -218,7 +224,10 @@ 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; @@ -239,7 +248,10 @@ 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; @@ -260,7 +272,10 @@ 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; @@ -281,7 +296,10 @@ 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; @@ -301,7 +319,10 @@ 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; @@ -329,7 +350,10 @@ public string Hex get => _hex; set { - if (_hex == value) return; + if (_hex == value) + { + return; + } ColorPickerRegister.ColorChanged = true; @@ -389,7 +413,9 @@ private static void OnShowTextBoxesChanged(DependencyObject d, DependencyPropert { if (d is ColorPicker colorPicker) // Force layout update on visibility change + { colorPicker.UpdateLayout(); + } } /// @@ -471,7 +497,10 @@ private void SetPreview() _ = CanvasPreview.Children.Add(rectangle); - if (ColorPickerRegister.ColorChanged) OnColorChanged(); + if (ColorPickerRegister.ColorChanged) + { + OnColorChanged(); + } } /// @@ -482,4 +511,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 bb83ab61..4e3cd4bb 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 63600391..48cc0cdb 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 b5c209bb..da65e679 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,9 +62,12 @@ 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; } @@ -87,17 +90,29 @@ 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; } @@ -113,7 +128,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; } /// @@ -127,7 +142,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 5e36052c..e56d42bb 100644 --- a/CommonControls/ColorSelection.xaml.cs +++ b/CommonControls/ColorSelection.xaml.cs @@ -128,7 +128,10 @@ 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; @@ -181,7 +184,10 @@ private static Dictionary InitiateColors() /// private void SwitchToStartColor() { - if (string.IsNullOrEmpty(StartColor)) return; + if (string.IsNullOrEmpty(StartColor)) + { + return; + } CmbColor.SelectedItem = typeof(Colors).GetProperty(StartColor); } @@ -196,4 +202,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 62c8b724..69174d6d 100644 --- a/CommonControls/Colorpick.cs +++ b/CommonControls/Colorpick.cs @@ -135,7 +135,10 @@ 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); } @@ -186,18 +189,23 @@ 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; @@ -207,15 +215,24 @@ 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 }; } @@ -232,18 +249,33 @@ 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); } @@ -258,7 +290,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)) }; } @@ -272,8 +304,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) }; } @@ -332,4 +364,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 608d5f21..b351aab9 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 cd147944..3db98fc4 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 c0ef5390..5f048ef3 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 df1b30e2..0d386a4f 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 e32ffd27..b7a34187 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 16e3af2f..7492d3ea 100644 --- a/CommonControls/DataListView.cs +++ b/CommonControls/DataListView.cs @@ -93,7 +93,10 @@ 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 { @@ -115,7 +118,10 @@ 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; @@ -190,7 +196,10 @@ public object Selection /// public void UpdateSelectedItem() { - if (_dataList.SelectedItem == null) return; + if (_dataList.SelectedItem == null) + { + return; + } var item = _dataList.SelectedItem; @@ -252,14 +261,20 @@ 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; } @@ -283,7 +298,10 @@ 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(); @@ -304,7 +322,10 @@ private void AddItem(string name) private void RemoveItem(DataItem item) { var check = Items.Remove(item); - if (!check) return; + if (!check) + { + return; + } _dataList.Removed(item); } @@ -384,16 +405,22 @@ 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 33cdb94f..48601a2e 100644 --- a/CommonControls/ExtendedGrid.cs +++ b/CommonControls/ExtendedGrid.cs @@ -187,7 +187,10 @@ 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; } @@ -203,7 +206,10 @@ 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; } @@ -211,4 +217,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 774a46c0..1d051cf4 100644 --- a/CommonControls/GlobalKeyHandler.cs +++ b/CommonControls/GlobalKeyHandler.cs @@ -104,12 +104,19 @@ 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 + } } /// @@ -118,26 +125,37 @@ 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 3adbdc20..f0dd2b16 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 b3b71842..c993814a 100644 --- a/CommonControls/ImageZoom.xaml.cs +++ b/CommonControls/ImageZoom.xaml.cs @@ -128,7 +128,10 @@ 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; @@ -283,12 +286,18 @@ 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 @@ -351,7 +360,10 @@ private void OnImageSourceChanged() BtmImage.StopAnimation(); BtmImage.Source = ItemsSource; - if (BtmImage.Source == null) return; + if (BtmImage.Source == null) + { + return; + } //reset Scaling Scale.ScaleX = 1; @@ -509,7 +521,10 @@ 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); @@ -603,11 +618,17 @@ 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) { @@ -615,12 +636,20 @@ 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(); @@ -654,4 +683,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 1380adad..44b66708 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 f8b074c3..5e958527 100644 --- a/CommonControls/ScrollingTextBoxes.cs +++ b/CommonControls/ScrollingTextBoxes.cs @@ -61,7 +61,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); CaretIndex = Text.Length; @@ -113,10 +116,13 @@ 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 52a7ba86..86d9fd40 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 9c6c9a57..b21660dc 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 26b7de89..3d5602b4 100644 --- a/CommonControls/Thumbnails.xaml.cs +++ b/CommonControls/Thumbnails.xaml.cs @@ -341,9 +341,15 @@ 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(); } @@ -356,11 +362,17 @@ 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); @@ -403,7 +415,10 @@ 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; @@ -420,18 +435,33 @@ 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) { @@ -448,12 +478,18 @@ 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(); @@ -479,7 +515,10 @@ 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; @@ -526,7 +565,10 @@ 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(() => @@ -537,6 +579,7 @@ 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; @@ -550,7 +593,10 @@ 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; @@ -561,6 +607,7 @@ private async Task LoadImageAsync(int key, string name, Panel exGrid) Grid.SetColumn(checkbox, key % ThumbWidth); _ = exGrid.Children.Add(checkbox); }); + } } /// @@ -615,9 +662,15 @@ 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]; @@ -627,7 +680,10 @@ 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); @@ -663,7 +719,10 @@ 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) @@ -673,10 +732,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); @@ -692,9 +751,15 @@ 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]; @@ -729,9 +794,15 @@ 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; + } } /// @@ -742,9 +813,15 @@ 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]; @@ -759,9 +836,15 @@ 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]; @@ -800,7 +883,10 @@ 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]; @@ -835,13 +921,19 @@ 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 a19dfb9f..9b87d2da 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 016cb249..6e286efe 100644 --- a/CommonLibraryTests/RenderingTests.cs +++ b/CommonLibraryTests/RenderingTests.cs @@ -1,9 +1,9 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +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,18 +59,18 @@ public void CompareImageProcessingSpeed() var imagePath = Path.Combine(SampleImagesFolder.FullName, "base.png"); // Measure processing time with DirectBitmap - Stopwatch stopwatch = new Stopwatch(); + var stopwatch = new Stopwatch(); stopwatch.Start(); ProcessWithDirectBitmap(imagePath); stopwatch.Stop(); - long directBitmapTime = stopwatch.ElapsedMilliseconds; + var directBitmapTime = stopwatch.ElapsedMilliseconds; // Measure processing time with SkiaSharp stopwatch.Reset(); stopwatch.Start(); - var img2= Tester.ProcessWithSkiaSharp(imagePath); + var img2 = Tester.ProcessWithSkiaSharp(imagePath); stopwatch.Stop(); - long skiaTime = stopwatch.ElapsedMilliseconds; + var skiaTime = stopwatch.ElapsedMilliseconds; // Log times for comparison Console.WriteLine($"DirectBitmap processing time: {directBitmapTime} ms"); @@ -84,15 +84,15 @@ private void ProcessWithDirectBitmap(string imagePath) { var btm = new Bitmap(imagePath); // Load the image using DirectBitmap (replace with your method) - DirectBitmap directBitmap = new DirectBitmap(btm); + var directBitmap = new DirectBitmap(btm); // Example operation: convert to grayscale - for (int x = 0; x < directBitmap.Width; x++) + for (var x = 0; x < directBitmap.Width; x++) { - for (int y = 0; y < directBitmap.Height; y++) + for (var y = 0; y < directBitmap.Height; y++) { - Color color = directBitmap.GetPixel(x, y); - int grayValue = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11); + var color = directBitmap.GetPixel(x, y); + var 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 b11fa37d..a4b4a814 100644 --- a/ImageCompare/AnalysisProcessing.cs +++ b/ImageCompare/AnalysisProcessing.cs @@ -38,14 +38,23 @@ 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); @@ -57,6 +66,7 @@ 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); @@ -71,6 +81,7 @@ internal static List GetSimilarity(List imagePaths) Trace.WriteLine(ex); throw new InvalidOperationException(ex.ToString()); } + } } catch (InvalidOperationException ex) { @@ -80,7 +91,10 @@ 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; @@ -164,7 +178,10 @@ 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); @@ -234,11 +251,14 @@ 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 6dcfce23..27812329 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 099df625..fc8042bf 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 0339fe8e..c32bbc35 100644 --- a/ImageCompare/ImageAnalysis.cs +++ b/ImageCompare/ImageAnalysis.cs @@ -76,10 +76,16 @@ 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; } @@ -95,10 +101,14 @@ 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); } @@ -125,7 +135,10 @@ 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); @@ -142,7 +155,9 @@ 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); } @@ -161,10 +176,14 @@ 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); } @@ -201,4 +220,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 3be54bcb..25fa70c1 100644 --- a/ImageCompare/ImageColor.cs +++ b/ImageCompare/ImageColor.cs @@ -102,11 +102,20 @@ 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; } @@ -122,11 +131,20 @@ 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; } @@ -157,4 +175,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 03c00a3b..d160111b 100644 --- a/ImageCompare/ImageColoring.cs +++ b/ImageCompare/ImageColoring.cs @@ -49,11 +49,17 @@ 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 }; @@ -79,6 +85,7 @@ 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); @@ -95,8 +102,9 @@ 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 d7a0b306..8de53bd2 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 4515eddc..b6f83276 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 60e8f940..13dce79c 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 b2405e3d..48846301 100644 --- a/ImageCompare/ImageDuplicate.cs +++ b/ImageCompare/ImageDuplicate.cs @@ -80,13 +80,19 @@ 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) && @@ -104,13 +110,19 @@ 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; @@ -153,4 +165,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 f0fbc6eb..2b066720 100644 --- a/ImageCompare/ImageDuplication.cs +++ b/ImageCompare/ImageDuplication.cs @@ -57,7 +57,10 @@ 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(); @@ -88,6 +91,7 @@ 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); @@ -110,6 +114,7 @@ private static List GetSortedGrayScaleValues() Trace.WriteLine(ex); throw new InvalidOperationException(ex.Message); } + } return imagePathsAndGrayValues; } @@ -144,7 +149,10 @@ private static IEnumerable> GetDuplicateGroups( currentDuplicates.Add(image); } - if (currentDuplicates.Count > 1) duplicateGroups.Add(currentDuplicates); + if (currentDuplicates.Count > 1) + { + duplicateGroups.Add(currentDuplicates); + } return duplicateGroups; } @@ -229,4 +237,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 ce75c535..b3aea331 100644 --- a/ImageCompare/ImageHelper.cs +++ b/ImageCompare/ImageHelper.cs @@ -47,10 +47,14 @@ 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); @@ -66,4 +70,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 a193a15a..48e993c8 100644 --- a/ImageCompare/ImageProcessing.cs +++ b/ImageCompare/ImageProcessing.cs @@ -46,10 +46,16 @@ 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; } @@ -86,9 +92,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; @@ -130,18 +136,21 @@ 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 e0570ea2..6975c801 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 79ee6009..ba811170 100644 --- a/ImageCompare/ImageSimilar.cs +++ b/ImageCompare/ImageSimilar.cs @@ -113,13 +113,25 @@ 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; } @@ -150,4 +162,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 33b0ddc8..c3eb9f66 100644 --- a/ImageCompare/ImageSimilarity.cs +++ b/ImageCompare/ImageSimilarity.cs @@ -50,13 +50,19 @@ 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); @@ -66,7 +72,10 @@ 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); @@ -87,7 +96,10 @@ 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); @@ -112,6 +124,7 @@ 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); @@ -133,6 +146,7 @@ private static List GetSortedGrayScaleValues() Trace.WriteLine(ex); throw new InvalidOperationException(ex.Message); } + } Trace.WriteLine(nameof(GetSortedGrayScaleValues)); Trace.WriteLine(imagePathsAndGrayValues.Count); @@ -186,4 +200,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 3dca3149..c42ed140 100644 --- a/ImageCompare/ImageSlider.cs +++ b/ImageCompare/ImageSlider.cs @@ -64,7 +64,9 @@ 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)) @@ -98,25 +100,41 @@ 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; } @@ -140,9 +158,13 @@ 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; } @@ -163,4 +185,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 9f7fa1f3..4e7ce93b 100644 --- a/Imaging/Cif.cs +++ b/Imaging/Cif.cs @@ -50,9 +50,14 @@ 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); @@ -72,9 +77,15 @@ 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; @@ -101,7 +112,10 @@ 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; } @@ -203,13 +217,22 @@ 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); @@ -237,15 +260,22 @@ 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; } @@ -262,7 +292,9 @@ 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) @@ -272,8 +304,12 @@ public Color GetColor(int id) } foreach (var (color, value) in _cifSorted) + { if (value.Contains(id)) + { return color; + } + } throw new KeyNotFoundException(nameof(id)); } @@ -285,14 +321,19 @@ 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; } @@ -314,7 +355,9 @@ 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); } @@ -341,7 +384,10 @@ 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); @@ -356,7 +402,10 @@ private Dictionary GetColorCount() /// private void Dispose(bool disposing) { - if (Disposed) return; + if (Disposed) + { + return; + } if (disposing) { @@ -393,4 +442,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 a47e53ca..15ab8c6b 100644 --- a/Imaging/CifImageData.cs +++ b/Imaging/CifImageData.cs @@ -23,29 +23,41 @@ 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 }; }; @@ -73,7 +85,10 @@ 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); @@ -81,4 +96,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 a7c7b8bb..004623ea 100644 --- a/Imaging/CifMetadata.cs +++ b/Imaging/CifMetadata.cs @@ -24,6 +24,7 @@ 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, @@ -31,6 +32,7 @@ public sealed class CifMetadata Compressed = parts[2] == ImagingResources.CifCompressed, CheckSum = checkSum }; + } return null; }; @@ -61,4 +63,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 463cddef..c115112e 100644 --- a/Imaging/CifProcessing.cs +++ b/Imaging/CifProcessing.cs @@ -39,7 +39,10 @@ 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); } @@ -55,13 +58,19 @@ 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; } @@ -84,13 +93,18 @@ 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 { @@ -102,9 +116,15 @@ 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; @@ -184,7 +204,10 @@ 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); @@ -213,4 +236,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 b76d603f..f1f755e9 100644 --- a/Imaging/ColorHsv.cs +++ b/Imaging/ColorHsv.cs @@ -59,11 +59,20 @@ 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); } @@ -127,13 +136,25 @@ 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; } @@ -155,10 +176,13 @@ 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; @@ -212,7 +236,10 @@ 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; @@ -248,7 +275,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(); @@ -272,7 +299,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 @@ -286,7 +313,10 @@ 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); @@ -346,8 +376,15 @@ 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); } @@ -397,20 +434,32 @@ 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; } @@ -435,4 +484,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 863819ef..48d59791 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 1fab2060..4d0a6e4f 100644 --- a/Imaging/DirectBitmap.cs +++ b/Imaging/DirectBitmap.cs @@ -167,7 +167,10 @@ 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; + } } /// @@ -180,7 +183,10 @@ 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; @@ -192,14 +198,22 @@ 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; + } } /// @@ -220,12 +234,18 @@ 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; + } + } } } @@ -249,14 +269,22 @@ 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; + } + } } } } @@ -270,7 +298,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(); } @@ -292,7 +320,9 @@ 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) { @@ -301,10 +331,11 @@ 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 @@ -313,11 +344,16 @@ 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]; + } + } } } @@ -330,7 +366,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); } @@ -341,7 +377,10 @@ 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]; @@ -366,7 +405,10 @@ 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]); } @@ -391,7 +433,10 @@ public override int GetHashCode() /// private void Dispose(bool disposing) { - if (Disposed) return; + if (Disposed) + { + return; + } if (disposing) { @@ -399,7 +444,10 @@ 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; @@ -417,4 +465,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 c3ae6772..3995976e 100644 --- a/Imaging/DirectBitmapImage.cs +++ b/Imaging/DirectBitmapImage.cs @@ -110,10 +110,12 @@ 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 @@ -122,7 +124,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 } @@ -202,7 +204,9 @@ 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 @@ -237,7 +241,9 @@ 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) { @@ -246,6 +252,7 @@ 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]; @@ -253,7 +260,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 @@ -269,12 +276,17 @@ 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]; + } + } } } @@ -307,12 +319,19 @@ 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; } @@ -325,4 +344,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 45e2d993..f5d6a5cc 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,11 +28,13 @@ 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, @@ -43,9 +45,16 @@ internal static Bitmap GenerateFilter(Bitmap image, Point? startPoint = null) { // Validate input - if (image == null) throw new ArgumentNullException(nameof(image)); + if (image == null) + { + throw new ArgumentNullException(nameof(image)); + } + + if (filter == FiltersType.None) + { + return image; // No filtering required + } - if (filter == FiltersType.None) return image; // No filtering required // Default start point var actualStartPoint = startPoint ?? new Point(0, 0); @@ -54,13 +63,15 @@ internal static Bitmap GenerateFilter(Bitmap image, var actualHeight = height ?? image.Height; // Apply filter - Bitmap filterBitmap = FiltersStream.FilterImage(image, filter, imageSettings); + var 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)), @@ -71,4 +82,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 540d54d1..0dda54db 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 249d73d7..0586f073 100644 --- a/Imaging/FiltersStream.cs +++ b/Imaging/FiltersStream.cs @@ -226,7 +226,10 @@ 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); @@ -235,9 +238,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))); @@ -339,7 +342,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 @@ -618,7 +621,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); @@ -685,7 +688,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; } @@ -784,16 +787,18 @@ 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; @@ -862,7 +867,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)); @@ -925,4 +930,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 21f2e025..68493525 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 05476456..523ee4f3 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 91dbb5f0..ed62c2bc 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,11 +100,13 @@ 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, @@ -369,7 +371,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. @@ -379,11 +381,13 @@ 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, @@ -570,4 +574,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 6ded0917..b0c4a084 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,11 +108,13 @@ 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, @@ -122,7 +124,7 @@ Bitmap GenerateTexture( object shapeParams = null); /// - /// Generates the texture overlay. + /// Generates the texture overlay. /// /// The image. /// The width. @@ -132,13 +134,15 @@ 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 472d0f23..83970e0c 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 b9235c08..72835ff4 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 36e0467f..ef9fe2ea 100644 --- a/Imaging/ImageGif.cs +++ b/Imaging/ImageGif.cs @@ -126,7 +126,9 @@ private async Task InitializeAsync() // Check if the image exists if (!File.Exists(GifSource)) // Log or show an error message + { return; + } try { @@ -134,7 +136,10 @@ 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); @@ -174,7 +179,10 @@ 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) { @@ -188,9 +196,13 @@ 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(); + } } /// @@ -198,11 +210,16 @@ 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]; + } } /// @@ -254,7 +271,10 @@ public void StopAnimation() /// if set to true [disposing]. private void Dispose(bool disposing) { - if (_isDisposed) return; + if (_isDisposed) + { + return; + } if (disposing) { @@ -275,4 +295,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 8eecaf8e..43c2dc08 100644 --- a/Imaging/ImageGifHandler.cs +++ b/Imaging/ImageGifHandler.cs @@ -154,7 +154,10 @@ 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); } @@ -169,7 +172,10 @@ 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); } @@ -181,7 +187,10 @@ 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); } @@ -201,7 +210,9 @@ 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); @@ -252,4 +263,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 ef7de49e..6d1f5593 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 d8b3b569..0fd4ceed 100644 --- a/Imaging/ImageGifMetadataExtractor.cs +++ b/Imaging/ImageGifMetadataExtractor.cs @@ -26,13 +26,11 @@ 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; @@ -42,7 +40,9 @@ 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,7 +58,9 @@ internal static ImageGifInfo ExtractGifMetadata(string filePath) : 0; if (metadata.HasGlobalColorTable) + { reader.BaseStream.Seek(metadata.GlobalColorTableSize, SeekOrigin.Current); + } while (reader.BaseStream.Position < reader.BaseStream.Length) { @@ -128,8 +130,7 @@ 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); @@ -143,7 +144,10 @@ 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); } @@ -176,7 +180,10 @@ 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); } @@ -192,11 +199,13 @@ 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 85331c22..9c479388 100644 --- a/Imaging/ImageHelper.cs +++ b/Imaging/ImageHelper.cs @@ -41,10 +41,12 @@ 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; @@ -74,7 +76,9 @@ 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; } @@ -121,16 +125,31 @@ 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 @@ -148,7 +167,9 @@ 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)); @@ -158,7 +179,9 @@ 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); + } } @@ -171,7 +194,10 @@ 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))); @@ -187,7 +213,10 @@ 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))); @@ -219,7 +248,10 @@ 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; @@ -239,7 +271,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); } /// @@ -287,10 +319,15 @@ 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 f0414687..7cd854a4 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 8e13fdb6..2633f906 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,7 +166,9 @@ 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; @@ -202,4 +204,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.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.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.EdgeEnhance, new HashSet { nameof(FiltersConfig.Factor), nameof(FiltersConfig.Bias) } @@ -430,16 +417,12 @@ 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 @@ -580,8 +563,12 @@ 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) { @@ -598,4 +585,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 b597d401..e27517b5 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,11 +142,13 @@ 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, @@ -522,7 +524,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. @@ -534,9 +536,11 @@ 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, @@ -848,4 +852,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 9154c71c..3bc98598 100644 --- a/Imaging/ImageStream.cs +++ b/Imaging/ImageStream.cs @@ -243,11 +243,16 @@ 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; @@ -379,7 +384,10 @@ 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) { @@ -400,8 +408,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. @@ -445,13 +453,18 @@ 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); @@ -496,7 +509,10 @@ 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; @@ -544,7 +560,10 @@ 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)); @@ -584,7 +603,9 @@ 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); @@ -608,14 +629,22 @@ 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; @@ -700,7 +729,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. @@ -710,11 +739,13 @@ 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, @@ -725,7 +756,10 @@ 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); @@ -782,7 +816,10 @@ 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)>(); @@ -795,7 +832,10 @@ 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; @@ -874,9 +914,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[] { @@ -888,4 +928,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 bc41351e..92e5094a 100644 --- a/Imaging/ImageStreamHsv.cs +++ b/Imaging/ImageStreamHsv.cs @@ -66,7 +66,10 @@ 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 => @@ -127,4 +130,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 99a39da9..db9d9e5c 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 948e66ba..3948f65e 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,34 +341,35 @@ 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, @@ -376,4 +377,4 @@ public static class ImagingResources TifExt }; } -} \ No newline at end of file +} diff --git a/Imaging/LayerSettings.cs b/Imaging/LayerSettings.cs index b12981aa..0b1a756c 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 ce8d0812..de9b3316 100644 --- a/Imaging/Lif.cs +++ b/Imaging/Lif.cs @@ -21,7 +21,10 @@ 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]; @@ -57,10 +60,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 83114670..21d92ec9 100644 --- a/Imaging/LifProcessing.cs +++ b/Imaging/LifProcessing.cs @@ -28,8 +28,12 @@ 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; @@ -63,10 +67,13 @@ 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); } @@ -99,20 +106,31 @@ 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; } @@ -123,4 +141,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 02c6391b..43828348 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 08fe4001..13de3283 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 ba65a429..6de56795 100644 --- a/Imaging/TextureAreas.cs +++ b/Imaging/TextureAreas.cs @@ -38,10 +38,14 @@ 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); @@ -79,7 +83,8 @@ 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 55bee6fe..dae57995 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 44dc5400..9a15fc6b 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,11 +176,13 @@ 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) @@ -260,4 +262,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 3a7f74bd..6bc17cd6 100644 --- a/Imaging/TextureStream.cs +++ b/Imaging/TextureStream.cs @@ -75,11 +75,17 @@ 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)); @@ -168,8 +174,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); @@ -218,10 +224,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); @@ -269,9 +275,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) + @@ -330,33 +336,41 @@ 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; } @@ -431,17 +445,21 @@ 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; @@ -456,7 +474,9 @@ 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 + } } /// @@ -512,4 +532,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 9daadb85..f739a379 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/RenderEngine/ImageProcessor.cs b/RenderEngine/ImageProcessor.cs index d6fb3641..ac1e30d8 100644 --- a/RenderEngine/ImageProcessor.cs +++ b/RenderEngine/ImageProcessor.cs @@ -36,3 +36,5 @@ // return processedBitmap; // } //} + + diff --git a/RenderEngine/Tester.cs b/RenderEngine/Tester.cs index 3aeb31ac..b5bcc8c5 100644 --- a/RenderEngine/Tester.cs +++ b/RenderEngine/Tester.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; +using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using SkiaSharp; @@ -16,19 +11,19 @@ public static class Tester public static WriteableBitmap ProcessWithSkiaSharp(string imagePath) { // Load the image using SkiaSharp - using SKBitmap bitmap = SKBitmap.Decode(imagePath); + using var bitmap = SKBitmap.Decode(imagePath); // Access the raw pixel data as a byte array (ARGB format) - byte[] pixelData = bitmap.Bytes; + var pixelData = bitmap.Bytes; // Loop through the pixels and apply the grayscale conversion - for (int i = 0; i < pixelData.Length; i += 4) // Skip 4 bytes per pixel (ARGB) + for (var i = 0; i < pixelData.Length; i += 4) // Skip 4 bytes per pixel (ARGB) { - byte blue = pixelData[i]; - byte green = pixelData[i + 1]; - byte red = pixelData[i + 2]; + var blue = pixelData[i]; + var green = pixelData[i + 1]; + var red = pixelData[i + 2]; // Calculate grayscale value (luminosity formula) - byte grayValue = (byte)(red * 0.3 + green * 0.59 + blue * 0.11); + var grayValue = (byte)((red * 0.3) + (green * 0.59) + (blue * 0.11)); // Set new grayscale value for all channels pixelData[i] = grayValue; // Blue channel @@ -38,10 +33,11 @@ public static WriteableBitmap ProcessWithSkiaSharp(string imagePath) } // Create a WriteableBitmap from the processed pixel data - WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap.Width, bitmap.Height, 96, 96, System.Windows.Media.PixelFormats.Bgra32, null); + var writeableBitmap = new WriteableBitmap(bitmap.Width, bitmap.Height, 96, 96, PixelFormats.Bgra32, null); // Write the pixel data to the WriteableBitmap - writeableBitmap.WritePixels(new System.Windows.Int32Rect(0, 0, bitmap.Width, bitmap.Height), pixelData, bitmap.Width * 4, 0); + writeableBitmap.WritePixels(new Int32Rect(0, 0, bitmap.Width, bitmap.Height), pixelData, bitmap.Width * 4, + 0); return writeableBitmap; } @@ -49,10 +45,10 @@ public static WriteableBitmap ProcessWithSkiaSharp(string imagePath) public static WriteableBitmap Render() { // Create a bitmap - SKBitmap bitmap = new SKBitmap(800, 600); + var bitmap = new SKBitmap(800, 600); // Create a canvas to draw on the bitmap - SKCanvas canvas = new SKCanvas(bitmap); + var canvas = new SKCanvas(bitmap); // Draw something or manipulate the bitmap canvas.Clear(SKColors.White);