diff --git a/.editorconfig b/.editorconfig index 753a4dbc2a..f84e6de2a0 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,5 +1,5 @@ -# Version: 2.1.0 (Using https://semver.org/) -# Updated: 2021-03-03 +# Version: 4.1.1 (Using https://semver.org/) +# Updated: 2022-05-23 # See https://github.com/RehanSaeed/EditorConfig/releases for release notes. # See https://github.com/RehanSaeed/EditorConfig for updates to this file. # See http://EditorConfig.org for more information about .editorconfig files. @@ -49,11 +49,11 @@ indent_size = 2 indent_size = 2 # Markdown Files -[*.md] +[*.{md,mdx}] trim_trailing_whitespace = false # Web Files -[*.{htm,html,js,jsm,ts,tsx,css,sass,scss,less,svg,vue}] +[*.{htm,html,js,jsm,ts,tsx,cjs,cts,ctsx,mjs,mts,mtsx,css,sass,scss,less,pcss,svg,vue}] indent_size = 2 # Batch Files @@ -75,7 +75,7 @@ indent_style = tab [*.{cs,csx,cake,vb,vbx}] # Default Severity for all .NET Code Style rules below -dotnet_analyzer_diagnostic.category-style.severity = warning +dotnet_analyzer_diagnostic.severity = warning ########################################## # Language Rules @@ -128,14 +128,15 @@ file_header_template = Copyright (c) Six Labors.\nLicensed under the Six Labors # dotnet_diagnostic.SA1636.severity = none # Undocumented -dotnet_style_operator_placement_when_wrapping = end_of_line +dotnet_style_operator_placement_when_wrapping = end_of_line:warning +csharp_style_prefer_null_check_over_type_check = true:warning # C# Style Rules # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/language-rules#c-style-rules [*.{cs,csx,cake}] # 'var' preferences -csharp_style_var_for_built_in_types = never -csharp_style_var_when_type_is_apparent = true:warning +csharp_style_var_for_built_in_types = false:warning +csharp_style_var_when_type_is_apparent = false:warning csharp_style_var_elsewhere = false:warning # Expression-bodied members csharp_style_expression_bodied_methods = true:warning @@ -200,12 +201,15 @@ dotnet_diagnostic.IDE0059.severity = suggestion # Organize using directives dotnet_sort_system_directives_first = true dotnet_separate_import_directive_groups = false +# Dotnet namespace options +dotnet_style_namespace_match_folder = true:suggestion +dotnet_diagnostic.IDE0130.severity = suggestion # C# formatting rules # https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#c-formatting-rules [*.{cs,csx,cake}] # Newline options -# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#new-line-options +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#new-line-options csharp_new_line_before_open_brace = all csharp_new_line_before_else = true csharp_new_line_before_catch = true @@ -214,7 +218,7 @@ csharp_new_line_before_members_in_object_initializers = true csharp_new_line_before_members_in_anonymous_types = true csharp_new_line_between_query_expression_clauses = true # Indentation options -# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#indentation-options +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#indentation-options csharp_indent_case_contents = true csharp_indent_switch_labels = true csharp_indent_labels = no_change @@ -222,7 +226,7 @@ csharp_indent_block_contents = true csharp_indent_braces = false csharp_indent_case_contents_when_block = false # Spacing options -# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#spacing-options +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#spacing-options csharp_space_after_cast = false csharp_space_after_keywords_in_control_flow_statements = true csharp_space_between_parentheses = false @@ -246,7 +250,7 @@ csharp_space_before_open_square_brackets = false csharp_space_between_empty_square_brackets = false csharp_space_between_square_brackets = false # Wrap options -# https://docs.microsoft.com/visualstudio/ide/editorconfig-formatting-conventions#wrap-options +# https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/formatting-rules#wrap-options csharp_preserve_single_line_statements = false csharp_preserve_single_line_blocks = true @@ -448,4 +452,4 @@ dotnet_naming_rule.parameters_rule.severity = warning # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. -########################################## +########################################## \ No newline at end of file diff --git a/shared-infrastructure b/shared-infrastructure index 86af5a8219..5eb77e2d9e 160000 --- a/shared-infrastructure +++ b/shared-infrastructure @@ -1 +1 @@ -Subproject commit 86af5a82198c21ce6889370428eb97d1fa7b41ff +Subproject commit 5eb77e2d9eb4f0ece012c996941ab78db1af2a41 diff --git a/src/ImageSharp/Advanced/AdvancedImageExtensions.cs b/src/ImageSharp/Advanced/AdvancedImageExtensions.cs index 8a7046c9ad..2fbb429957 100644 --- a/src/ImageSharp/Advanced/AdvancedImageExtensions.cs +++ b/src/ImageSharp/Advanced/AdvancedImageExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Text; using System.Threading; @@ -34,11 +35,11 @@ namespace SixLabors.ImageSharp.Advanced IImageFormat format = source.GetConfiguration().ImageFormatsManager.FindFormatByFileExtension(ext); if (format is null) { - var sb = new StringBuilder(); - sb.AppendLine($"No encoder was found for extension '{ext}'. Registered encoders include:"); + StringBuilder sb = new(); + sb.AppendLine(CultureInfo.InvariantCulture, $"No encoder was found for extension '{ext}'. Registered encoders include:"); foreach (IImageFormat fmt in source.GetConfiguration().ImageFormats) { - sb.AppendFormat(" - {0} : {1}{2}", fmt.Name, string.Join(", ", fmt.FileExtensions), Environment.NewLine); + sb.AppendFormat(CultureInfo.InvariantCulture, " - {0} : {1}{2}", fmt.Name, string.Join(", ", fmt.FileExtensions), Environment.NewLine); } throw new NotSupportedException(sb.ToString()); @@ -48,11 +49,11 @@ namespace SixLabors.ImageSharp.Advanced if (encoder is null) { - var sb = new StringBuilder(); - sb.AppendLine($"No encoder was found for extension '{ext}' using image format '{format.Name}'. Registered encoders include:"); + StringBuilder sb = new(); + sb.AppendLine(CultureInfo.InvariantCulture, $"No encoder was found for extension '{ext}' using image format '{format.Name}'. Registered encoders include:"); foreach (KeyValuePair enc in source.GetConfiguration().ImageFormatsManager.ImageEncoders) { - sb.AppendFormat(" - {0} : {1}{2}", enc.Key, enc.Value.GetType().Name, Environment.NewLine); + sb.AppendFormat(CultureInfo.InvariantCulture, " - {0} : {1}{2}", enc.Key, enc.Value.GetType().Name, Environment.NewLine); } throw new NotSupportedException(sb.ToString()); @@ -116,6 +117,7 @@ namespace SixLabors.ImageSharp.Advanced /// Certain Image Processors may invalidate the returned and all it's buffers, /// therefore it's not recommended to mutate the image while holding a reference to it's . /// + /// Thrown when the in . public static IMemoryGroup GetPixelMemoryGroup(this ImageFrame source) where TPixel : unmanaged, IPixel => source?.PixelBuffer.FastMemoryGroup.View ?? throw new ArgumentNullException(nameof(source)); @@ -131,13 +133,14 @@ namespace SixLabors.ImageSharp.Advanced /// Certain Image Processors may invalidate the returned and all it's buffers, /// therefore it's not recommended to mutate the image while holding a reference to it's . /// + /// Thrown when the in . public static IMemoryGroup GetPixelMemoryGroup(this Image source) where TPixel : unmanaged, IPixel => source?.Frames.RootFrame.GetPixelMemoryGroup() ?? throw new ArgumentNullException(nameof(source)); /// /// Gets the representation of the pixels as a of contiguous memory - /// at row beginning from the the first pixel on that row. + /// at row beginning from the first pixel on that row. /// /// The type of the pixel. /// The source. @@ -154,8 +157,8 @@ namespace SixLabors.ImageSharp.Advanced } /// - /// Gets the representation of the pixels as of of contiguous memory - /// at row beginning from the the first pixel on that row. + /// Gets the representation of the pixels as of contiguous memory + /// at row beginning from the first pixel on that row. /// /// The type of the pixel. /// The source. diff --git a/src/ImageSharp/Advanced/PreserveAttribute.cs b/src/ImageSharp/Advanced/PreserveAttribute.cs index d543a043c8..5e3a712707 100644 --- a/src/ImageSharp/Advanced/PreserveAttribute.cs +++ b/src/ImageSharp/Advanced/PreserveAttribute.cs @@ -1,6 +1,8 @@ // Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System; + namespace SixLabors.ImageSharp.Advanced { /// @@ -8,7 +10,8 @@ namespace SixLabors.ImageSharp.Advanced /// The only thing that matters is the class name. /// There is no need to use or inherit from the PreserveAttribute class in each environment. /// - internal sealed class PreserveAttribute : System.Attribute + [AttributeUsage(AttributeTargets.Method)] + internal sealed class PreserveAttribute : Attribute { } } diff --git a/src/ImageSharp/Color/Color.cs b/src/ImageSharp/Color/Color.cs index d8fb348913..17e0964d0a 100644 --- a/src/ImageSharp/Color/Color.cs +++ b/src/ImageSharp/Color/Color.cs @@ -151,7 +151,7 @@ namespace SixLabors.ImageSharp [MethodImpl(InliningOptions.ShortMethod)] public static Color ParseHex(string hex) { - var rgba = Rgba32.ParseHex(hex); + Rgba32 rgba = Rgba32.ParseHex(hex); return new Color(rgba); } @@ -193,6 +193,7 @@ namespace SixLabors.ImageSharp /// /// The . /// + /// Input string is not in the correct format. public static Color Parse(string input) { Guard.NotNull(input, nameof(input)); @@ -241,7 +242,7 @@ namespace SixLabors.ImageSharp /// The color having it's alpha channel altered. public Color WithAlpha(float alpha) { - var v = (Vector4)this; + Vector4 v = (Vector4)this; v.W = alpha; return new Color(v); } @@ -286,14 +287,10 @@ namespace SixLabors.ImageSharp /// Bulk converts a span of to a span of a specified type. /// /// The pixel type to convert to. - /// The configuration. /// The source color span. /// The destination pixel span. [MethodImpl(InliningOptions.ShortMethod)] - public static void ToPixel( - Configuration configuration, - ReadOnlySpan source, - Span destination) + public static void ToPixel(ReadOnlySpan source, Span destination) where TPixel : unmanaged, IPixel { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); diff --git a/src/ImageSharp/ColorSpaces/CieLab.cs b/src/ImageSharp/ColorSpaces/CieLab.cs index b72a2eecd4..bc84342dec 100644 --- a/src/ImageSharp/ColorSpaces/CieLab.cs +++ b/src/ImageSharp/ColorSpaces/CieLab.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -19,29 +19,6 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public static readonly CieXyz DefaultWhitePoint = Illuminants.D50; - /// - /// Gets the lightness dimension. - /// A value usually ranging between 0 (black), 100 (diffuse white) or higher (specular white). - /// - public readonly float L; - - /// - /// Gets the a color component. - /// A value usually ranging from -100 to 100. Negative is green, positive magenta. - /// - public readonly float A; - - /// - /// Gets the b color component. - /// A value usually ranging from -100 to 100. Negative is blue, positive is yellow - /// - public readonly float B; - - /// - /// Gets the reference white point of this color - /// - public readonly CieXyz WhitePoint; - /// /// Initializes a new instance of the struct. /// @@ -95,6 +72,29 @@ namespace SixLabors.ImageSharp.ColorSpaces this.WhitePoint = whitePoint; } + /// + /// Gets the lightness dimension. + /// A value usually ranging between 0 (black), 100 (diffuse white) or higher (specular white). + /// + public readonly float L { get; } + + /// + /// Gets the a color component. + /// A value usually ranging from -100 to 100. Negative is green, positive magenta. + /// + public readonly float A { get; } + + /// + /// Gets the b color component. + /// A value usually ranging from -100 to 100. Negative is blue, positive is yellow + /// + public readonly float B { get; } + + /// + /// Gets the reference white point of this color + /// + public readonly CieXyz WhitePoint { get; } + /// /// Compares two objects for equality. /// @@ -128,12 +128,10 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] - public bool Equals(CieLab other) - { - return this.L.Equals(other.L) - && this.A.Equals(other.A) - && this.B.Equals(other.B) - && this.WhitePoint.Equals(other.WhitePoint); - } + public bool Equals(CieLab other) => + this.L.Equals(other.L) + && this.A.Equals(other.A) + && this.B.Equals(other.B) + && this.WhitePoint.Equals(other.WhitePoint); } } diff --git a/src/ImageSharp/ColorSpaces/CieLch.cs b/src/ImageSharp/ColorSpaces/CieLch.cs index 899c7d8dbc..0c46e9b7cc 100644 --- a/src/ImageSharp/ColorSpaces/CieLch.cs +++ b/src/ImageSharp/ColorSpaces/CieLch.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -19,31 +19,8 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public static readonly CieXyz DefaultWhitePoint = Illuminants.D50; - private static readonly Vector3 Min = new Vector3(0, -200, 0); - private static readonly Vector3 Max = new Vector3(100, 200, 360); - - /// - /// Gets the lightness dimension. - /// A value ranging between 0 (black), 100 (diffuse white) or higher (specular white). - /// - public readonly float L; - - /// - /// Gets the a chroma component. - /// A value ranging from 0 to 200. - /// - public readonly float C; - - /// - /// Gets the h° hue component in degrees. - /// A value ranging from 0 to 360. - /// - public readonly float H; - - /// - /// Gets the reference white point of this color - /// - public readonly CieXyz WhitePoint; + private static readonly Vector3 Min = new(0, -200, 0); + private static readonly Vector3 Max = new(100, 200, 360); /// /// Initializes a new instance of the struct. @@ -97,6 +74,29 @@ namespace SixLabors.ImageSharp.ColorSpaces this.WhitePoint = whitePoint; } + /// + /// Gets the lightness dimension. + /// A value ranging between 0 (black), 100 (diffuse white) or higher (specular white). + /// + public readonly float L { get; } + + /// + /// Gets the a chroma component. + /// A value ranging from 0 to 200. + /// + public readonly float C { get; } + + /// + /// Gets the h° hue component in degrees. + /// A value ranging from 0 to 360. + /// + public readonly float H { get; } + + /// + /// Gets the reference white point of this color + /// + public readonly CieXyz WhitePoint { get; } + /// /// Compares two objects for equality. /// @@ -121,9 +121,7 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public override int GetHashCode() - { - return HashCode.Combine(this.L, this.C, this.H, this.WhitePoint); - } + => HashCode.Combine(this.L, this.C, this.H, this.WhitePoint); /// public override string ToString() => FormattableString.Invariant($"CieLch({this.L:#0.##}, {this.C:#0.##}, {this.H:#0.##})"); @@ -135,12 +133,10 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(CieLch other) - { - return this.L.Equals(other.L) - && this.C.Equals(other.C) - && this.H.Equals(other.H) - && this.WhitePoint.Equals(other.WhitePoint); - } + => this.L.Equals(other.L) + && this.C.Equals(other.C) + && this.H.Equals(other.H) + && this.WhitePoint.Equals(other.WhitePoint); /// /// Computes the saturation of the color (chroma normalized by lightness) diff --git a/src/ImageSharp/ColorSpaces/CieLchuv.cs b/src/ImageSharp/ColorSpaces/CieLchuv.cs index 2a41fd490c..2227b60225 100644 --- a/src/ImageSharp/ColorSpaces/CieLchuv.cs +++ b/src/ImageSharp/ColorSpaces/CieLchuv.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -13,8 +13,8 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public readonly struct CieLchuv : IEquatable { - private static readonly Vector3 Min = new Vector3(0, -200, 0); - private static readonly Vector3 Max = new Vector3(100, 200, 360); + private static readonly Vector3 Min = new(0, -200, 0); + private static readonly Vector3 Max = new(100, 200, 360); /// /// D50 standard illuminant. @@ -22,29 +22,6 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public static readonly CieXyz DefaultWhitePoint = Illuminants.D65; - /// - /// Gets the lightness dimension. - /// A value ranging between 0 (black), 100 (diffuse white) or higher (specular white). - /// - public readonly float L; - - /// - /// Gets the a chroma component. - /// A value ranging from 0 to 200. - /// - public readonly float C; - - /// - /// Gets the h° hue component in degrees. - /// A value ranging from 0 to 360. - /// - public readonly float H; - - /// - /// Gets the reference white point of this color - /// - public readonly CieXyz WhitePoint; - /// /// Initializes a new instance of the struct. /// @@ -98,6 +75,29 @@ namespace SixLabors.ImageSharp.ColorSpaces this.WhitePoint = whitePoint; } + /// + /// Gets the lightness dimension. + /// A value ranging between 0 (black), 100 (diffuse white) or higher (specular white). + /// + public readonly float L { get; } + + /// + /// Gets the a chroma component. + /// A value ranging from 0 to 200. + /// + public readonly float C { get; } + + /// + /// Gets the h° hue component in degrees. + /// A value ranging from 0 to 360. + /// + public readonly float H { get; } + + /// + /// Gets the reference white point of this color + /// + public readonly CieXyz WhitePoint { get; } + /// /// Compares two objects for equality. /// @@ -130,12 +130,10 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(CieLchuv other) - { - return this.L.Equals(other.L) - && this.C.Equals(other.C) - && this.H.Equals(other.H) - && this.WhitePoint.Equals(other.WhitePoint); - } + => this.L.Equals(other.L) + && this.C.Equals(other.C) + && this.H.Equals(other.H) + && this.WhitePoint.Equals(other.WhitePoint); /// /// Computes the saturation of the color (chroma normalized by lightness) diff --git a/src/ImageSharp/ColorSpaces/CieLuv.cs b/src/ImageSharp/ColorSpaces/CieLuv.cs index a45042ba85..32481bcb52 100644 --- a/src/ImageSharp/ColorSpaces/CieLuv.cs +++ b/src/ImageSharp/ColorSpaces/CieLuv.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -21,29 +21,6 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public static readonly CieXyz DefaultWhitePoint = Illuminants.D65; - /// - /// Gets the lightness dimension - /// A value usually ranging between 0 and 100. - /// - public readonly float L; - - /// - /// Gets the blue-yellow chromaticity coordinate of the given whitepoint. - /// A value usually ranging between -100 and 100. - /// - public readonly float U; - - /// - /// Gets the red-green chromaticity coordinate of the given whitepoint. - /// A value usually ranging between -100 and 100. - /// - public readonly float V; - - /// - /// Gets the reference white point of this color - /// - public readonly CieXyz WhitePoint; - /// /// Initializes a new instance of the struct. /// @@ -96,6 +73,29 @@ namespace SixLabors.ImageSharp.ColorSpaces this.WhitePoint = whitePoint; } + /// + /// Gets the lightness dimension + /// A value usually ranging between 0 and 100. + /// + public readonly float L { get; } + + /// + /// Gets the blue-yellow chromaticity coordinate of the given whitepoint. + /// A value usually ranging between -100 and 100. + /// + public readonly float U { get; } + + /// + /// Gets the red-green chromaticity coordinate of the given whitepoint. + /// A value usually ranging between -100 and 100. + /// + public readonly float V { get; } + + /// + /// Gets the reference white point of this color + /// + public readonly CieXyz WhitePoint { get; } + /// /// Compares two objects for equality. /// @@ -130,11 +130,9 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(CieLuv other) - { - return this.L.Equals(other.L) - && this.U.Equals(other.U) - && this.V.Equals(other.V) - && this.WhitePoint.Equals(other.WhitePoint); - } + => this.L.Equals(other.L) + && this.U.Equals(other.U) + && this.V.Equals(other.V) + && this.WhitePoint.Equals(other.WhitePoint); } } diff --git a/src/ImageSharp/ColorSpaces/CieXyy.cs b/src/ImageSharp/ColorSpaces/CieXyy.cs index 9306606db9..6bbcad075c 100644 --- a/src/ImageSharp/ColorSpaces/CieXyy.cs +++ b/src/ImageSharp/ColorSpaces/CieXyy.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -13,24 +13,6 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public readonly struct CieXyy : IEquatable { - /// - /// Gets the X chrominance component. - /// A value usually ranging between 0 and 1. - /// - public readonly float X; - - /// - /// Gets the Y chrominance component. - /// A value usually ranging between 0 and 1. - /// - public readonly float Y; - - /// - /// Gets the Y luminance component. - /// A value usually ranging between 0 and 1. - /// - public readonly float Yl; - /// /// Initializes a new instance of the struct. /// @@ -60,6 +42,24 @@ namespace SixLabors.ImageSharp.ColorSpaces this.Yl = vector.Z; } + /// + /// Gets the X chrominance component. + /// A value usually ranging between 0 and 1. + /// + public readonly float X { get; } + + /// + /// Gets the Y chrominance component. + /// A value usually ranging between 0 and 1. + /// + public readonly float Y { get; } + + /// + /// Gets the Y luminance component. + /// A value usually ranging between 0 and 1. + /// + public readonly float Yl { get; } + /// /// Compares two objects for equality. /// @@ -94,10 +94,8 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(CieXyy other) - { - return this.X.Equals(other.X) - && this.Y.Equals(other.Y) - && this.Yl.Equals(other.Yl); - } + => this.X.Equals(other.X) + && this.Y.Equals(other.Y) + && this.Yl.Equals(other.Yl); } } diff --git a/src/ImageSharp/ColorSpaces/CieXyz.cs b/src/ImageSharp/ColorSpaces/CieXyz.cs index e52904c558..b767128438 100644 --- a/src/ImageSharp/ColorSpaces/CieXyz.cs +++ b/src/ImageSharp/ColorSpaces/CieXyz.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -13,24 +13,6 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public readonly struct CieXyz : IEquatable { - /// - /// Gets the X component. A mix (a linear combination) of cone response curves chosen to be nonnegative. - /// A value usually ranging between 0 and 1. - /// - public readonly float X; - - /// - /// Gets the Y luminance component. - /// A value usually ranging between 0 and 1. - /// - public readonly float Y; - - /// - /// Gets the Z component. Quasi-equal to blue stimulation, or the S cone response. - /// A value usually ranging between 0 and 1. - /// - public readonly float Z; - /// /// Initializes a new instance of the struct. /// @@ -56,6 +38,24 @@ namespace SixLabors.ImageSharp.ColorSpaces this.Z = vector.Z; } + /// + /// Gets the X component. A mix (a linear combination) of cone response curves chosen to be nonnegative. + /// A value usually ranging between 0 and 1. + /// + public readonly float X { get; } + + /// + /// Gets the Y luminance component. + /// A value usually ranging between 0 and 1. + /// + public readonly float Y { get; } + + /// + /// Gets the Z component. Quasi-equal to blue stimulation, or the S cone response. + /// A value usually ranging between 0 and 1. + /// + public readonly float Z { get; } + /// /// Compares two objects for equality. /// @@ -83,7 +83,7 @@ namespace SixLabors.ImageSharp.ColorSpaces /// /// The . [MethodImpl(InliningOptions.ShortMethod)] - public Vector3 ToVector3() => new Vector3(this.X, this.Y, this.Z); + public Vector3 ToVector3() => new(this.X, this.Y, this.Z); /// public override int GetHashCode() => HashCode.Combine(this.X, this.Y, this.Z); @@ -97,10 +97,8 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(CieXyz other) - { - return this.X.Equals(other.X) - && this.Y.Equals(other.Y) - && this.Z.Equals(other.Z); - } + => this.X.Equals(other.X) + && this.Y.Equals(other.Y) + && this.Z.Equals(other.Z); } } diff --git a/src/ImageSharp/ColorSpaces/Cmyk.cs b/src/ImageSharp/ColorSpaces/Cmyk.cs index cd2899ee7d..fad331101c 100644 --- a/src/ImageSharp/ColorSpaces/Cmyk.cs +++ b/src/ImageSharp/ColorSpaces/Cmyk.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -15,30 +15,6 @@ namespace SixLabors.ImageSharp.ColorSpaces private static readonly Vector4 Min = Vector4.Zero; private static readonly Vector4 Max = Vector4.One; - /// - /// Gets the cyan color component. - /// A value ranging between 0 and 1. - /// - public readonly float C; - - /// - /// Gets the magenta color component. - /// A value ranging between 0 and 1. - /// - public readonly float M; - - /// - /// Gets the yellow color component. - /// A value ranging between 0 and 1. - /// - public readonly float Y; - - /// - /// Gets the keyline black color component. - /// A value ranging between 0 and 1. - /// - public readonly float K; - /// /// Initializes a new instance of the struct. /// @@ -66,6 +42,30 @@ namespace SixLabors.ImageSharp.ColorSpaces this.K = vector.W; } + /// + /// Gets the cyan color component. + /// A value ranging between 0 and 1. + /// + public readonly float C { get; } + + /// + /// Gets the magenta color component. + /// A value ranging between 0 and 1. + /// + public readonly float M { get; } + + /// + /// Gets the yellow color component. + /// A value ranging between 0 and 1. + /// + public readonly float Y { get; } + + /// + /// Gets the keyline black color component. + /// A value ranging between 0 and 1. + /// + public readonly float K { get; } + /// /// Compares two objects for equality. /// @@ -101,11 +101,9 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(Cmyk other) - { - return this.C.Equals(other.C) - && this.M.Equals(other.M) - && this.Y.Equals(other.Y) - && this.K.Equals(other.K); - } + => this.C.Equals(other.C) + && this.M.Equals(other.M) + && this.Y.Equals(other.Y) + && this.K.Equals(other.K); } } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Adapt.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Adapt.cs index 60ae18b5c9..d200aa83ec 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Adapt.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Adapt.cs @@ -150,9 +150,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion return color; } - var linearInput = this.ToLinearRgb(color); + var linearInput = ToLinearRgb(color); LinearRgb linearOutput = this.Adapt(linearInput); - return this.ToRgb(linearOutput); + return ToRgb(linearOutput); } } } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLab.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLab.cs index 1a7c627db5..c3dd3b473f 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLab.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLab.cs @@ -12,11 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - /// - /// The converter for converting between CieLch to CieLab. - /// - private static readonly CieLchToCieLabConverter CieLchToCieLabConverter = new CieLchToCieLabConverter(); - /// /// Converts a into a . /// @@ -58,7 +53,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in CieLchuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -91,7 +86,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in CieLuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -124,7 +119,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -190,7 +185,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in Cmyk color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -222,7 +217,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in Hsl color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -255,7 +250,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in Hsv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -287,7 +282,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in HunterLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -320,7 +315,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in Lms color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -353,7 +348,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in LinearRgb color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -386,7 +381,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in Rgb color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } @@ -419,7 +414,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLab ToCieLab(in YCbCr color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLab(xyzColor); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLch.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLch.cs index 06ff11b1ec..ec7d48b783 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLch.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLch.cs @@ -12,11 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - /// - /// The converter for converting between CieLab to CieLch. - /// - private static readonly CieLabToCieLchConverter CieLabToCieLchConverter = new CieLabToCieLchConverter(); - /// /// Converts a into a /// @@ -123,7 +118,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLch ToCieLch(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + var xyzColor = ToCieXyz(color); return this.ToCieLch(xyzColor); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLchuv.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLchuv.cs index 5752cb9b11..52c092a2e8 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLchuv.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLchuv.cs @@ -12,11 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - /// - /// The converter for converting between CieLab to CieLchuv. - /// - private static readonly CieLuvToCieLchuvConverter CieLuvToCieLchuvConverter = new CieLuvToCieLchuvConverter(); - /// /// Converts a into a /// @@ -24,7 +19,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in CieLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLchuv(xyzColor); } @@ -57,7 +52,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in CieLch color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLchuv(xyzColor); } @@ -123,7 +118,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = ToCieXyz(color); return this.ToCieLchuv(xyzColor); } @@ -156,7 +151,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in CieXyz color) { - var luvColor = this.ToCieLuv(color); + CieLuv luvColor = this.ToCieLuv(color); return this.ToCieLchuv(luvColor); } @@ -189,7 +184,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in Cmyk color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLchuv(xyzColor); } @@ -222,7 +217,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in Hsl color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLchuv(xyzColor); } @@ -255,7 +250,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in Hsv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLchuv(xyzColor); } @@ -288,7 +283,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in HunterLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLchuv(xyzColor); } @@ -321,7 +316,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in LinearRgb color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLchuv(xyzColor); } @@ -354,7 +349,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in Lms color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLchuv(xyzColor); } @@ -387,7 +382,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in Rgb color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLchuv(xyzColor); } @@ -420,7 +415,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLchuv ToCieLchuv(in YCbCr color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLchuv(xyzColor); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLuv.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLuv.cs index 486924b9aa..572d8875db 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLuv.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieLuv.cs @@ -12,8 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - private static readonly CieLchuvToCieLuvConverter CieLchuvToCieLuvConverter = new CieLchuvToCieLuvConverter(); - /// /// Converts a into a . /// @@ -21,7 +19,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in CieLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLuv(xyzColor); } @@ -53,7 +51,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in CieLch color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLuv(xyzColor); } @@ -120,7 +118,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = ToCieXyz(color); return this.ToCieLuv(xyzColor); } @@ -187,7 +185,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in Cmyk color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLuv(xyzColor); } @@ -219,7 +217,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in Hsl color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLuv(xyzColor); } @@ -251,7 +249,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in Hsv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLuv(xyzColor); } @@ -283,7 +281,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in HunterLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLuv(xyzColor); } @@ -315,7 +313,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in Lms color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLuv(xyzColor); } @@ -347,7 +345,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in LinearRgb color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLuv(xyzColor); } @@ -379,7 +377,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in Rgb color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLuv(xyzColor); } @@ -411,7 +409,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieLuv ToCieLuv(in YCbCr color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCieLuv(xyzColor); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyy.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyy.cs index 603308751c..b5d655e680 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyy.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyy.cs @@ -12,8 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - private static readonly CieXyzAndCieXyyConverter CieXyzAndCieXyyConverter = new CieXyzAndCieXyyConverter(); - /// /// Converts a into a /// @@ -21,9 +19,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in CieLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -54,9 +52,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in CieLch color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -87,9 +85,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in CieLchuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -120,9 +118,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in CieLuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -151,14 +149,14 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public CieXyy ToCieXyy(in CieXyz color) => CieXyzAndCieXyyConverter.Convert(color); + public static CieXyy ToCieXyy(in CieXyz color) => CieXyzAndCieXyyConverter.Convert(color); /// /// Performs the bulk conversion from into /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -170,7 +168,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref CieXyz sp = ref Unsafe.Add(ref sourceRef, i); ref CieXyy dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToCieXyy(sp); + dp = ToCieXyy(sp); } } @@ -181,9 +179,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in Cmyk color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -214,9 +212,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(Hsl color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -247,9 +245,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in Hsv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -280,9 +278,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in HunterLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -313,9 +311,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in LinearRgb color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -346,9 +344,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in Lms color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -379,9 +377,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in Rgb color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// @@ -412,9 +410,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyy ToCieXyy(in YCbCr color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); - return this.ToCieXyy(xyzColor); + return ToCieXyy(xyzColor); } /// diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyz.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyz.cs index 242392acc0..d1f0ca489d 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyz.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.CieXyz.cs @@ -12,12 +12,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - private static readonly CieLabToCieXyzConverter CieLabToCieXyzConverter = new CieLabToCieXyzConverter(); - - private static readonly CieLuvToCieXyzConverter CieLuvToCieXyzConverter = new CieLuvToCieXyzConverter(); - - private static readonly HunterLabToCieXyzConverter - HunterLabToCieXyzConverter = new HunterLabToCieXyzConverter(); + private static readonly HunterLabToCieXyzConverter HunterLabToCieXyzConverter = new(); private LinearRgbToCieXyzConverter linearRgbToCieXyzConverter; @@ -166,18 +161,17 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public CieXyz ToCieXyz(in CieXyy color) - { + public static CieXyz ToCieXyz(in CieXyy color) + // Conversion - return CieXyzAndCieXyyConverter.Convert(color); - } + => CieXyzAndCieXyyConverter.Convert(color); /// /// Performs the bulk conversion from into . /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -189,7 +183,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref CieXyy sp = ref Unsafe.Add(ref sourceRef, i); ref CieXyz dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToCieXyz(sp); + dp = ToCieXyz(sp); } } @@ -200,7 +194,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(in Cmyk color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return this.ToCieXyz(rgb); } @@ -233,7 +227,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(in Hsl color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return this.ToCieXyz(rgb); } @@ -267,7 +261,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion public CieXyz ToCieXyz(in Hsv color) { // Conversion - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return this.ToCieXyz(rgb); } @@ -367,9 +361,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The color to convert. /// The public CieXyz ToCieXyz(in Lms color) - { - return this.cieXyzAndLmsConverter.Convert(color); - } + => this.cieXyzAndLmsConverter.Convert(color); /// /// Performs the bulk conversion from into . @@ -432,7 +424,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public CieXyz ToCieXyz(in YCbCr color) { - var rgb = this.ToRgb(color); + Rgb rgb = this.ToRgb(color); return this.ToCieXyz(rgb); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Cmyk.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Cmyk.cs index 664511be9a..152a7f7fc6 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Cmyk.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Cmyk.cs @@ -12,8 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - private static readonly CmykAndRgbConverter CmykAndRgbConverter = new CmykAndRgbConverter(); - /// /// Converts a into a . /// @@ -21,7 +19,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Cmyk ToCmyk(in CieLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCmyk(xyzColor); } @@ -54,7 +52,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Cmyk ToCmyk(in CieLch color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCmyk(xyzColor); } @@ -87,7 +85,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Cmyk ToCmyk(in CieLchuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCmyk(xyzColor); } @@ -120,7 +118,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Cmyk ToCmyk(in CieLuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCmyk(xyzColor); } @@ -153,7 +151,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Cmyk ToCmyk(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = ToCieXyz(color); return this.ToCmyk(xyzColor); } @@ -186,7 +184,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Cmyk ToCmyk(in CieXyz color) { - var rgb = this.ToRgb(color); + Rgb rgb = this.ToRgb(color); return CmykAndRgbConverter.Convert(rgb); } @@ -217,9 +215,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Cmyk ToCmyk(in Hsl color) + public static Cmyk ToCmyk(in Hsl color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return CmykAndRgbConverter.Convert(rgb); } @@ -229,7 +227,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -241,7 +239,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Hsl sp = ref Unsafe.Add(ref sourceRef, i); ref Cmyk dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToCmyk(sp); + dp = ToCmyk(sp); } } @@ -250,9 +248,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Cmyk ToCmyk(in Hsv color) + public static Cmyk ToCmyk(in Hsv color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return CmykAndRgbConverter.Convert(rgb); } @@ -262,7 +260,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -274,7 +272,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Hsv sp = ref Unsafe.Add(ref sourceRef, i); ref Cmyk dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToCmyk(sp); + dp = ToCmyk(sp); } } @@ -285,7 +283,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Cmyk ToCmyk(in HunterLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCmyk(xyzColor); } @@ -316,9 +314,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Cmyk ToCmyk(in LinearRgb color) + public static Cmyk ToCmyk(in LinearRgb color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return CmykAndRgbConverter.Convert(rgb); } @@ -328,7 +326,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -340,7 +338,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref LinearRgb sp = ref Unsafe.Add(ref sourceRef, i); ref Cmyk dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToCmyk(sp); + dp = ToCmyk(sp); } } @@ -351,7 +349,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Cmyk ToCmyk(in Lms color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToCmyk(xyzColor); } @@ -382,14 +380,14 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Cmyk ToCmyk(in Rgb color) => CmykAndRgbConverter.Convert(color); + public static Cmyk ToCmyk(in Rgb color) => CmykAndRgbConverter.Convert(color); /// /// Performs the bulk conversion from into /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -401,7 +399,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Rgb sp = ref Unsafe.Add(ref sourceRef, i); ref Cmyk dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToCmyk(sp); + dp = ToCmyk(sp); } } @@ -412,7 +410,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Cmyk ToCmyk(in YCbCr color) { - var rgb = this.ToRgb(color); + Rgb rgb = this.ToRgb(color); return CmykAndRgbConverter.Convert(rgb); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsl.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsl.cs index 666a6b03cf..19e1bef0d0 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsl.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsl.cs @@ -12,8 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - private static readonly HslAndRgbConverter HslAndRgbConverter = new HslAndRgbConverter(); - /// /// Converts a into a . /// @@ -21,7 +19,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsl ToHsl(in CieLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsl(xyzColor); } @@ -54,7 +52,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsl ToHsl(in CieLch color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsl(xyzColor); } @@ -87,7 +85,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsl ToHsl(in CieLchuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsl(xyzColor); } @@ -120,7 +118,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsl ToHsl(in CieLuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsl(xyzColor); } @@ -153,7 +151,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsl ToHsl(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = ToCieXyz(color); return this.ToHsl(xyzColor); } @@ -186,7 +184,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsl ToHsl(in CieXyz color) { - var rgb = this.ToRgb(color); + Rgb rgb = this.ToRgb(color); return HslAndRgbConverter.Convert(rgb); } @@ -217,9 +215,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Hsl ToHsl(in Cmyk color) + public static Hsl ToHsl(in Cmyk color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return HslAndRgbConverter.Convert(rgb); } @@ -229,7 +227,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -241,7 +239,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Cmyk sp = ref Unsafe.Add(ref sourceRef, i); ref Hsl dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToHsl(sp); + dp = ToHsl(sp); } } @@ -250,9 +248,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Hsl ToHsl(in Hsv color) + public static Hsl ToHsl(in Hsv color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return HslAndRgbConverter.Convert(rgb); } @@ -262,7 +260,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -274,7 +272,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Hsv sp = ref Unsafe.Add(ref sourceRef, i); ref Hsl dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToHsl(sp); + dp = ToHsl(sp); } } @@ -285,7 +283,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsl ToHsl(in HunterLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsl(xyzColor); } @@ -316,9 +314,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Hsl ToHsl(in LinearRgb color) + public static Hsl ToHsl(in LinearRgb color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return HslAndRgbConverter.Convert(rgb); } @@ -328,7 +326,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -340,7 +338,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref LinearRgb sp = ref Unsafe.Add(ref sourceRef, i); ref Hsl dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToHsl(sp); + dp = ToHsl(sp); } } @@ -351,7 +349,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsl ToHsl(Lms color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsl(xyzColor); } @@ -382,14 +380,14 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Hsl ToHsl(in Rgb color) => HslAndRgbConverter.Convert(color); + public static Hsl ToHsl(in Rgb color) => HslAndRgbConverter.Convert(color); /// /// Performs the bulk conversion from into . /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -401,7 +399,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Rgb sp = ref Unsafe.Add(ref sourceRef, i); ref Hsl dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToHsl(sp); + dp = ToHsl(sp); } } @@ -412,7 +410,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsl ToHsl(in YCbCr color) { - var rgb = this.ToRgb(color); + Rgb rgb = this.ToRgb(color); return HslAndRgbConverter.Convert(rgb); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsv.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsv.cs index 615a26e36c..c6a3a68d78 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsv.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Hsv.cs @@ -12,8 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - private static readonly HsvAndRgbConverter HsvAndRgbConverter = new HsvAndRgbConverter(); - /// /// Converts a into a /// @@ -21,7 +19,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(in CieLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); } @@ -54,7 +52,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(in CieLch color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); } @@ -87,7 +85,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(in CieLchuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); } @@ -120,7 +118,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(in CieLuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); } @@ -153,7 +151,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = ToCieXyz(color); return this.ToHsv(xyzColor); } @@ -186,7 +184,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(in CieXyz color) { - var rgb = this.ToRgb(color); + Rgb rgb = this.ToRgb(color); return HsvAndRgbConverter.Convert(rgb); } @@ -217,9 +215,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Hsv ToHsv(in Cmyk color) + public static Hsv ToHsv(in Cmyk color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return HsvAndRgbConverter.Convert(rgb); } @@ -229,7 +227,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -241,7 +239,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Cmyk sp = ref Unsafe.Add(ref sourceRef, i); ref Hsv dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToHsv(sp); + dp = ToHsv(sp); } } @@ -250,9 +248,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Hsv ToHsv(in Hsl color) + public static Hsv ToHsv(in Hsl color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return HsvAndRgbConverter.Convert(rgb); } @@ -262,7 +260,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors. - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -274,7 +272,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Hsl sp = ref Unsafe.Add(ref sourceRef, i); ref Hsv dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToHsv(sp); + dp = ToHsv(sp); } } @@ -285,7 +283,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(in HunterLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); } @@ -316,9 +314,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Hsv ToHsv(in LinearRgb color) + public static Hsv ToHsv(in LinearRgb color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return HsvAndRgbConverter.Convert(rgb); } @@ -328,7 +326,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -340,7 +338,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref LinearRgb sp = ref Unsafe.Add(ref sourceRef, i); ref Hsv dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToHsv(sp); + dp = ToHsv(sp); } } @@ -351,7 +349,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(Lms color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToHsv(xyzColor); } @@ -382,14 +380,14 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Hsv ToHsv(in Rgb color) => HsvAndRgbConverter.Convert(color); + public static Hsv ToHsv(in Rgb color) => HsvAndRgbConverter.Convert(color); /// /// Performs the bulk conversion from into /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -401,7 +399,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Rgb sp = ref Unsafe.Add(ref sourceRef, i); ref Hsv dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToHsv(sp); + dp = ToHsv(sp); } } @@ -412,7 +410,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Hsv ToHsv(in YCbCr color) { - var rgb = this.ToRgb(color); + Rgb rgb = this.ToRgb(color); return HsvAndRgbConverter.Convert(rgb); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.HunterLab.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.HunterLab.cs index ad2fbd626d..0e880ed591 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.HunterLab.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.HunterLab.cs @@ -336,7 +336,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public HunterLab ToHunterLab(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + var xyzColor = ToCieXyz(color); return this.ToHunterLab(xyzColor); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.LinearRgb.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.LinearRgb.cs index c317c8e8bb..c5801b0b40 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.LinearRgb.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.LinearRgb.cs @@ -12,8 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - private static readonly RgbToLinearRgbConverter RgbToLinearRgbConverter = new RgbToLinearRgbConverter(); - /// /// Performs the bulk conversion from into . /// @@ -145,7 +143,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors. /// The span to the destination colors. - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -157,7 +155,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Cmyk sp = ref Unsafe.Add(ref sourceRef, i); ref LinearRgb dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToLinearRgb(sp); + dp = ToLinearRgb(sp); } } @@ -166,7 +164,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors. /// The span to the destination colors. - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -178,7 +176,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Hsl sp = ref Unsafe.Add(ref sourceRef, i); ref LinearRgb dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToLinearRgb(sp); + dp = ToLinearRgb(sp); } } @@ -187,7 +185,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors. /// The span to the destination colors. - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -199,7 +197,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Hsv sp = ref Unsafe.Add(ref sourceRef, i); ref LinearRgb dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToLinearRgb(sp); + dp = ToLinearRgb(sp); } } @@ -250,7 +248,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -262,7 +260,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Rgb sp = ref Unsafe.Add(ref sourceRef, i); ref LinearRgb dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToLinearRgb(sp); + dp = ToLinearRgb(sp); } } @@ -294,7 +292,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public LinearRgb ToLinearRgb(in CieLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToLinearRgb(xyzColor); } @@ -305,7 +303,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public LinearRgb ToLinearRgb(in CieLch color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToLinearRgb(xyzColor); } @@ -316,7 +314,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public LinearRgb ToLinearRgb(in CieLchuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToLinearRgb(xyzColor); } @@ -327,7 +325,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public LinearRgb ToLinearRgb(in CieLuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToLinearRgb(xyzColor); } @@ -338,7 +336,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public LinearRgb ToLinearRgb(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = ToCieXyz(color); return this.ToLinearRgb(xyzColor); } @@ -361,10 +359,10 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public LinearRgb ToLinearRgb(in Cmyk color) + public static LinearRgb ToLinearRgb(in Cmyk color) { - var rgb = this.ToRgb(color); - return this.ToLinearRgb(rgb); + Rgb rgb = ToRgb(color); + return ToLinearRgb(rgb); } /// @@ -372,10 +370,10 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public LinearRgb ToLinearRgb(in Hsl color) + public static LinearRgb ToLinearRgb(in Hsl color) { - var rgb = this.ToRgb(color); - return this.ToLinearRgb(rgb); + Rgb rgb = ToRgb(color); + return ToLinearRgb(rgb); } /// @@ -383,10 +381,10 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public LinearRgb ToLinearRgb(in Hsv color) + public static LinearRgb ToLinearRgb(in Hsv color) { - var rgb = this.ToRgb(color); - return this.ToLinearRgb(rgb); + Rgb rgb = ToRgb(color); + return ToLinearRgb(rgb); } /// @@ -396,7 +394,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public LinearRgb ToLinearRgb(in HunterLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToLinearRgb(xyzColor); } @@ -407,7 +405,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public LinearRgb ToLinearRgb(in Lms color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToLinearRgb(xyzColor); } @@ -416,11 +414,8 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public LinearRgb ToLinearRgb(in Rgb color) - { - // Conversion - return RgbToLinearRgbConverter.Convert(color); - } + public static LinearRgb ToLinearRgb(in Rgb color) + => RgbToLinearRgbConverter.Convert(color); /// /// Converts a into a . @@ -429,8 +424,8 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public LinearRgb ToLinearRgb(in YCbCr color) { - var rgb = this.ToRgb(color); - return this.ToLinearRgb(rgb); + Rgb rgb = this.ToRgb(color); + return ToLinearRgb(rgb); } } } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Lms.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Lms.cs index be36c46dc3..dbaaa4dd0e 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Lms.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Lms.cs @@ -336,7 +336,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Lms ToLms(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + var xyzColor = ToCieXyz(color); return this.ToLms(xyzColor); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Rgb.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Rgb.cs index cfb6d3b76b..461ce8c21c 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Rgb.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.Rgb.cs @@ -12,8 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - private static readonly LinearRgbToRgbConverter LinearRgbToRgbConverter = new LinearRgbToRgbConverter(); - /// /// Performs the bulk conversion from into /// @@ -145,7 +143,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -157,7 +155,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Cmyk sp = ref Unsafe.Add(ref sourceRef, i); ref Rgb dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToRgb(sp); + dp = ToRgb(sp); } } @@ -166,7 +164,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -178,7 +176,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Hsv sp = ref Unsafe.Add(ref sourceRef, i); ref Rgb dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToRgb(sp); + dp = ToRgb(sp); } } @@ -187,7 +185,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -199,7 +197,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Hsl sp = ref Unsafe.Add(ref sourceRef, i); ref Rgb dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToRgb(sp); + dp = ToRgb(sp); } } @@ -229,7 +227,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -241,7 +239,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref LinearRgb sp = ref Unsafe.Add(ref sourceRef, i); ref Rgb dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToRgb(sp); + dp = ToRgb(sp); } } @@ -294,7 +292,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Rgb ToRgb(in CieLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToRgb(xyzColor); } @@ -305,7 +303,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Rgb ToRgb(in CieLch color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToRgb(xyzColor); } @@ -316,7 +314,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Rgb ToRgb(in CieLchuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToRgb(xyzColor); } @@ -327,7 +325,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Rgb ToRgb(in CieLuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToRgb(xyzColor); } @@ -338,7 +336,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Rgb ToRgb(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = ToCieXyz(color); return this.ToRgb(xyzColor); } @@ -350,10 +348,10 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion public Rgb ToRgb(in CieXyz color) { // Conversion - var linear = this.ToLinearRgb(color); + LinearRgb linear = this.ToLinearRgb(color); // Compand - return this.ToRgb(linear); + return ToRgb(linear); } /// @@ -361,33 +359,21 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Rgb ToRgb(in Cmyk color) - { - // Conversion - return CmykAndRgbConverter.Convert(color); - } + public static Rgb ToRgb(in Cmyk color) => CmykAndRgbConverter.Convert(color); /// /// Converts a into a /// /// The color to convert. /// The - public Rgb ToRgb(in Hsv color) - { - // Conversion - return HsvAndRgbConverter.Convert(color); - } + public static Rgb ToRgb(in Hsv color) => HsvAndRgbConverter.Convert(color); /// /// Converts a into a /// /// The color to convert. /// The - public Rgb ToRgb(in Hsl color) - { - // Conversion - return HslAndRgbConverter.Convert(color); - } + public static Rgb ToRgb(in Hsl color) => HslAndRgbConverter.Convert(color); /// /// Converts a into a @@ -396,7 +382,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Rgb ToRgb(in HunterLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToRgb(xyzColor); } @@ -405,11 +391,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public Rgb ToRgb(in LinearRgb color) - { - // Conversion - return LinearRgbToRgbConverter.Convert(color); - } + public static Rgb ToRgb(in LinearRgb color) => LinearRgbToRgbConverter.Convert(color); /// /// Converts a into a @@ -418,7 +400,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public Rgb ToRgb(in Lms color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToRgb(xyzColor); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.YCbCr.cs b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.YCbCr.cs index db6dc21338..48bb8ebd61 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.YCbCr.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/ColorSpaceConverter.YCbCr.cs @@ -12,8 +12,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public partial class ColorSpaceConverter { - private static readonly YCbCrAndRgbConverter YCbCrAndRgbConverter = new YCbCrAndRgbConverter(); - /// /// Performs the bulk conversion from into . /// @@ -124,7 +122,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -136,7 +134,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Cmyk sp = ref Unsafe.Add(ref sourceRef, i); ref YCbCr dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToYCbCr(sp); + dp = ToYCbCr(sp); } } @@ -145,7 +143,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -157,7 +155,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Hsl sp = ref Unsafe.Add(ref sourceRef, i); ref YCbCr dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToYCbCr(sp); + dp = ToYCbCr(sp); } } @@ -166,7 +164,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -178,7 +176,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Hsv sp = ref Unsafe.Add(ref sourceRef, i); ref YCbCr dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToYCbCr(sp); + dp = ToYCbCr(sp); } } @@ -208,7 +206,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -220,7 +218,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref LinearRgb sp = ref Unsafe.Add(ref sourceRef, i); ref YCbCr dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToYCbCr(sp); + dp = ToYCbCr(sp); } } @@ -250,7 +248,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The span to the source colors /// The span to the destination colors - public void Convert(ReadOnlySpan source, Span destination) + public static void Convert(ReadOnlySpan source, Span destination) { Guard.DestinationShouldNotBeTooShort(source, destination, nameof(destination)); int count = source.Length; @@ -262,7 +260,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { ref Rgb sp = ref Unsafe.Add(ref sourceRef, i); ref YCbCr dp = ref Unsafe.Add(ref destRef, i); - dp = this.ToYCbCr(sp); + dp = ToYCbCr(sp); } } @@ -273,7 +271,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public YCbCr ToYCbCr(in CieLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToYCbCr(xyzColor); } @@ -285,7 +283,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public YCbCr ToYCbCr(in CieLch color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToYCbCr(xyzColor); } @@ -297,7 +295,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public YCbCr ToYCbCr(in CieLuv color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToYCbCr(xyzColor); } @@ -309,7 +307,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public YCbCr ToYCbCr(in CieXyy color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = ToCieXyz(color); return this.ToYCbCr(xyzColor); } @@ -321,7 +319,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public YCbCr ToYCbCr(in CieXyz color) { - var rgb = this.ToRgb(color); + Rgb rgb = this.ToRgb(color); return YCbCrAndRgbConverter.Convert(rgb); } @@ -331,9 +329,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public YCbCr ToYCbCr(in Cmyk color) + public static YCbCr ToYCbCr(in Cmyk color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return YCbCrAndRgbConverter.Convert(rgb); } @@ -343,9 +341,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public YCbCr ToYCbCr(in Hsl color) + public static YCbCr ToYCbCr(in Hsl color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return YCbCrAndRgbConverter.Convert(rgb); } @@ -355,9 +353,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public YCbCr ToYCbCr(in Hsv color) + public static YCbCr ToYCbCr(in Hsv color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return YCbCrAndRgbConverter.Convert(rgb); } @@ -369,7 +367,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public YCbCr ToYCbCr(in HunterLab color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToYCbCr(xyzColor); } @@ -379,9 +377,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public YCbCr ToYCbCr(in LinearRgb color) + public static YCbCr ToYCbCr(in LinearRgb color) { - var rgb = this.ToRgb(color); + Rgb rgb = ToRgb(color); return YCbCrAndRgbConverter.Convert(rgb); } @@ -393,7 +391,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The public YCbCr ToYCbCr(in Lms color) { - var xyzColor = this.ToCieXyz(color); + CieXyz xyzColor = this.ToCieXyz(color); return this.ToYCbCr(xyzColor); } @@ -403,6 +401,6 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// The color to convert. /// The - public YCbCr ToYCbCr(in Rgb color) => YCbCrAndRgbConverter.Convert(color); + public static YCbCr ToYCbCr(in Rgb color) => YCbCrAndRgbConverter.Convert(color); } } diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieXyChromaticityCoordinates.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieXyChromaticityCoordinates.cs index 728d7cd222..bb021f6100 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieXyChromaticityCoordinates.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/CieXyChromaticityCoordinates.cs @@ -12,13 +12,25 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// public readonly struct CieXyChromaticityCoordinates : IEquatable { + /// + /// Initializes a new instance of the struct. + /// + /// Chromaticity coordinate x (usually from 0 to 1) + /// Chromaticity coordinate y (usually from 0 to 1) + [MethodImpl(InliningOptions.ShortMethod)] + public CieXyChromaticityCoordinates(float x, float y) + { + this.X = x; + this.Y = y; + } + /// /// Gets the chromaticity X-coordinate. /// /// /// Ranges usually from 0 to 1. /// - public readonly float X; + public readonly float X { get; } /// /// Gets the chromaticity Y-coordinate @@ -26,19 +38,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Ranges usually from 0 to 1. /// - public readonly float Y; - - /// - /// Initializes a new instance of the struct. - /// - /// Chromaticity coordinate x (usually from 0 to 1) - /// Chromaticity coordinate y (usually from 0 to 1) - [MethodImpl(InliningOptions.ShortMethod)] - public CieXyChromaticityCoordinates(float x, float y) - { - this.X = x; - this.Y = y; - } + public readonly float Y { get; } /// /// Compares two objects for equality. @@ -49,7 +49,8 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// True if the current left is equal to the parameter; otherwise, false. /// [MethodImpl(InliningOptions.ShortMethod)] - public static bool operator ==(CieXyChromaticityCoordinates left, CieXyChromaticityCoordinates right) => left.Equals(right); + public static bool operator ==(CieXyChromaticityCoordinates left, CieXyChromaticityCoordinates right) + => left.Equals(right); /// /// Compares two objects for inequality @@ -60,20 +61,25 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// True if the current left is unequal to the parameter; otherwise, false. /// [MethodImpl(InliningOptions.ShortMethod)] - public static bool operator !=(CieXyChromaticityCoordinates left, CieXyChromaticityCoordinates right) => !left.Equals(right); + public static bool operator !=(CieXyChromaticityCoordinates left, CieXyChromaticityCoordinates right) + => !left.Equals(right); /// [MethodImpl(InliningOptions.ShortMethod)] - public override int GetHashCode() => HashCode.Combine(this.X, this.Y); + public override int GetHashCode() + => HashCode.Combine(this.X, this.Y); /// - public override string ToString() => FormattableString.Invariant($"CieXyChromaticityCoordinates({this.X:#0.##}, {this.Y:#0.##})"); + public override string ToString() + => FormattableString.Invariant($"CieXyChromaticityCoordinates({this.X:#0.##}, {this.Y:#0.##})"); /// - public override bool Equals(object obj) => obj is CieXyChromaticityCoordinates other && this.Equals(other); + public override bool Equals(object obj) + => obj is CieXyChromaticityCoordinates other && this.Equals(other); /// [MethodImpl(InliningOptions.ShortMethod)] - public bool Equals(CieXyChromaticityCoordinates other) => this.X.Equals(other.X) && this.Y.Equals(other.Y); + public bool Equals(CieXyChromaticityCoordinates other) + => this.X.Equals(other.X) && this.Y.Equals(other.Y); } } diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CIeLchToCieLabConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CIeLchToCieLabConverter.cs index 6485da0762..9da7826c40 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CIeLchToCieLabConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CIeLchToCieLabConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -9,7 +9,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Converts from to . /// - internal sealed class CieLchToCieLabConverter + internal static class CieLchToCieLabConverter { /// /// Performs the conversion from the input to an instance of type. @@ -17,7 +17,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public CieLab Convert(in CieLch input) + public static CieLab Convert(in CieLch input) { // Conversion algorithm described here: // https://en.wikipedia.org/wiki/Lab_color_space#Cylindrical_representation:_CIELCh_or_CIEHLC diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLabToCieLchConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLabToCieLchConverter.cs index 0aefeda856..da7d3f509e 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLabToCieLchConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLabToCieLchConverter.cs @@ -9,7 +9,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Converts from to . /// - internal sealed class CieLabToCieLchConverter + internal static class CieLabToCieLchConverter { /// /// Performs the conversion from the input to an instance of type. @@ -17,7 +17,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public CieLch Convert(in CieLab input) + public static CieLch Convert(in CieLab input) { // Conversion algorithm described here: // https://en.wikipedia.org/wiki/Lab_color_space#Cylindrical_representation:_CIELCh_or_CIEHLC diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLabToCieXyzConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLabToCieXyzConverter.cs index 3634ebe99b..e852e61bea 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLabToCieXyzConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLabToCieXyzConverter.cs @@ -9,7 +9,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Converts from to . /// - internal sealed class CieLabToCieXyzConverter + internal static class CieLabToCieXyzConverter { /// /// Performs the conversion from the input to an instance of type. @@ -17,7 +17,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public CieXyz Convert(in CieLab input) + public static CieXyz Convert(in CieLab input) { // Conversion algorithm described here: http://www.brucelindbloom.com/index.html?Eqn_Lab_to_XYZ.html float l = input.L, a = input.A, b = input.B; @@ -32,10 +32,10 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion float yr = l > CieConstants.Kappa * CieConstants.Epsilon ? Numerics.Pow3((l + 16F) / 116F) : l / CieConstants.Kappa; float zr = fz3 > CieConstants.Epsilon ? fz3 : ((116F * fz) - 16F) / CieConstants.Kappa; - var wxyz = new Vector3(input.WhitePoint.X, input.WhitePoint.Y, input.WhitePoint.Z); + Vector3 wxyz = new(input.WhitePoint.X, input.WhitePoint.Y, input.WhitePoint.Z); // Avoids XYZ coordinates out range (restricted by 0 and XYZ reference white) - var xyzr = Vector3.Clamp(new Vector3(xr, yr, zr), Vector3.Zero, Vector3.One); + Vector3 xyzr = Vector3.Clamp(new Vector3(xr, yr, zr), Vector3.Zero, Vector3.One); Vector3 xyz = xyzr * wxyz; return new CieXyz(xyz); diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLchuvToCieLuvConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLchuvToCieLuvConverter.cs index fc064a6ded..c2f2e5d294 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLchuvToCieLuvConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLchuvToCieLuvConverter.cs @@ -9,7 +9,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Converts from to . /// - internal sealed class CieLchuvToCieLuvConverter + internal static class CieLchuvToCieLuvConverter { /// /// Performs the conversion from the input to an instance of type. @@ -17,7 +17,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public CieLuv Convert(in CieLchuv input) + public static CieLuv Convert(in CieLchuv input) { // Conversion algorithm described here: // https://en.wikipedia.org/wiki/CIELUV#Cylindrical_representation_.28CIELCH.29 diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLuvToCieLchuvConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLuvToCieLchuvConverter.cs index d69fb46970..f894d748ba 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLuvToCieLchuvConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLuvToCieLchuvConverter.cs @@ -9,7 +9,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Converts from to . /// - internal sealed class CieLuvToCieLchuvConverter + internal static class CieLuvToCieLchuvConverter { /// /// Performs the conversion from the input to an instance of type. @@ -17,7 +17,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public CieLchuv Convert(in CieLuv input) + public static CieLchuv Convert(in CieLuv input) { // Conversion algorithm described here: // https://en.wikipedia.org/wiki/CIELUV#Cylindrical_representation_.28CIELCH.29 diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLuvToCieXyzConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLuvToCieXyzConverter.cs index 0b4a4a9b85..aa12e511e5 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLuvToCieXyzConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieLuvToCieXyzConverter.cs @@ -8,14 +8,14 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Converts from to . /// - internal sealed class CieLuvToCieXyzConverter + internal static class CieLuvToCieXyzConverter { /// /// Performs the conversion from the input to an instance of type. /// /// The input color instance. /// The converted result - public CieXyz Convert(in CieLuv input) + public static CieXyz Convert(in CieLuv input) { // Conversion algorithm described here: http://www.brucelindbloom.com/index.html?Eqn_Luv_to_XYZ.html float l = input.L, u = input.U, v = input.V; diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieXyzAndCieXyyConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieXyzAndCieXyyConverter.cs index 5db91eb754..619d04d0cc 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieXyzAndCieXyyConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieXyzAndCieXyyConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -10,7 +10,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// Color converter between CIE XYZ and CIE xyY. /// for formulas. /// - internal sealed class CieXyzAndCieXyyConverter + internal static class CieXyzAndCieXyyConverter { /// /// Performs the conversion from the input to an instance of type. @@ -18,7 +18,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public CieXyy Convert(in CieXyz input) + public static CieXyy Convert(in CieXyz input) { float x = input.X / (input.X + input.Y + input.Z); float y = input.Y / (input.X + input.Y + input.Z); @@ -37,7 +37,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public CieXyz Convert(in CieXyy input) + public static CieXyz Convert(in CieXyy input) { if (MathF.Abs(input.Y) < Constants.Epsilon) { diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieXyzAndLmsConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieXyzAndLmsConverter.cs index 533d94465b..ac9f1f6363 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieXyzAndLmsConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CieXyzAndLmsConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System.Numerics; @@ -49,7 +49,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion [MethodImpl(InliningOptions.ShortMethod)] public Lms Convert(in CieXyz input) { - var vector = Vector3.Transform(input.ToVector3(), this.transformationMatrix); + Vector3 vector = Vector3.Transform(input.ToVector3(), this.transformationMatrix); return new Lms(vector); } @@ -62,7 +62,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion [MethodImpl(InliningOptions.ShortMethod)] public CieXyz Convert(in Lms input) { - var vector = Vector3.Transform(input.ToVector3(), this.inverseTransformationMatrix); + Vector3 vector = Vector3.Transform(input.ToVector3(), this.inverseTransformationMatrix); return new CieXyz(vector); } diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CmykAndRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CmykAndRgbConverter.cs index 20a03fb41d..31b11575b6 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CmykAndRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/CmykAndRgbConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -10,7 +10,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Color converter between and . /// - internal sealed class CmykAndRgbConverter + internal static class CmykAndRgbConverter { /// /// Performs the conversion from the input to an instance of type. @@ -18,7 +18,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public Rgb Convert(in Cmyk input) + public static Rgb Convert(in Cmyk input) { Vector3 rgb = (Vector3.One - new Vector3(input.C, input.M, input.Y)) * (Vector3.One - new Vector3(input.K)); return new Rgb(rgb); @@ -30,13 +30,13 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result. [MethodImpl(InliningOptions.ShortMethod)] - public Cmyk Convert(in Rgb input) + public static Cmyk Convert(in Rgb input) { // To CMY Vector3 cmy = Vector3.One - input.ToVector3(); // To CMYK - var k = new Vector3(MathF.Min(cmy.X, MathF.Min(cmy.Y, cmy.Z))); + Vector3 k = new(MathF.Min(cmy.X, MathF.Min(cmy.Y, cmy.Z))); if (MathF.Abs(k.X - 1F) < Constants.Epsilon) { diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HslAndRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HslAndRgbConverter.cs index c5a599e9e5..70cc064a8b 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HslAndRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HslAndRgbConverter.cs @@ -10,7 +10,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// Color converter between HSL and Rgb /// See for formulas. /// - internal sealed class HslAndRgbConverter + internal static class HslAndRgbConverter { /// /// Performs the conversion from the input to an instance of type. @@ -18,7 +18,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public Rgb Convert(in Hsl input) + public static Rgb Convert(in Hsl input) { float rangedH = input.H / 360F; float r = 0; @@ -53,7 +53,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public Hsl Convert(in Rgb input) + public static Hsl Convert(in Rgb input) { float r = input.R; float g = input.G; diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HsvAndRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HsvAndRgbConverter.cs index de187ee593..9b01c80887 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HsvAndRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HsvAndRgbConverter.cs @@ -10,7 +10,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// Color converter between HSV and Rgb /// See for formulas. /// - internal sealed class HsvAndRgbConverter + internal static class HsvAndRgbConverter { /// /// Performs the conversion from the input to an instance of type. @@ -18,7 +18,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public Rgb Convert(in Hsv input) + public static Rgb Convert(in Hsv input) { float s = input.S; float v = input.V; @@ -85,7 +85,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public Hsv Convert(in Rgb input) + public static Hsv Convert(in Rgb input) { float r = input.R; float g = input.G; diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HunterLabToCieXyzConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HunterLabToCieXyzConverter.cs index a804d1d5f5..ead2f37d85 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HunterLabToCieXyzConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/HunterLabToCieXyzConverter.cs @@ -9,7 +9,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Color converter between and /// - internal sealed class HunterLabToCieXyzConverter : CieXyzAndHunterLabConverterBase + internal class HunterLabToCieXyzConverter : CieXyzAndHunterLabConverterBase { /// /// Performs the conversion from the input to an instance of type. @@ -17,7 +17,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result [MethodImpl(InliningOptions.ShortMethod)] - public CieXyz Convert(in HunterLab input) + public static CieXyz Convert(in HunterLab input) { // Conversion algorithm described here: http://en.wikipedia.org/wiki/Lab_color_space#Hunter_Lab float l = input.L, a = input.A, b = input.B; diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbAndCieXyzConverterBase.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbAndCieXyzConverterBase.cs index 8a406cb333..ac0ab73119 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbAndCieXyzConverterBase.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbAndCieXyzConverterBase.cs @@ -28,25 +28,22 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion float yb = chromaticity.B.Y; float mXr = xr / yr; - const float Yr = 1; float mZr = (1 - xr - yr) / yr; float mXg = xg / yg; - const float Yg = 1; float mZg = (1 - xg - yg) / yg; float mXb = xb / yb; - const float Yb = 1; float mZb = (1 - xb - yb) / yb; - var xyzMatrix = new Matrix4x4 + Matrix4x4 xyzMatrix = new() { M11 = mXr, M21 = mXg, M31 = mXb, - M12 = Yr, - M22 = Yg, - M32 = Yb, + M12 = 1F, + M22 = 1F, + M32 = 1F, M13 = mZr, M23 = mZg, M33 = mZb, @@ -55,7 +52,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion Matrix4x4.Invert(xyzMatrix, out Matrix4x4 inverseXyzMatrix); - var vector = Vector3.Transform(workingSpace.WhitePoint.ToVector3(), inverseXyzMatrix); + Vector3 vector = Vector3.Transform(workingSpace.WhitePoint.ToVector3(), inverseXyzMatrix); // Use transposed Rows/Columns // TODO: Is there a built in method for this multiplication? @@ -64,9 +61,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion M11 = vector.X * mXr, M21 = vector.Y * mXg, M31 = vector.Z * mXb, - M12 = vector.X * Yr, - M22 = vector.Y * Yg, - M32 = vector.Z * Yb, + M12 = vector.X * 1, + M22 = vector.Y * 1, + M32 = vector.Z * 1, M13 = vector.X * mZr, M23 = vector.Y * mZg, M33 = vector.Z * mZb, diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbToCieXyzConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbToCieXyzConverter.cs index f124fdd807..5f0755969b 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbToCieXyzConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbToCieXyzConverter.cs @@ -46,7 +46,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion { DebugGuard.IsTrue(input.WorkingSpace.Equals(this.SourceWorkingSpace), nameof(input.WorkingSpace), "Input and source working spaces must be equal."); - var vector = Vector3.Transform(input.ToVector3(), this.conversionMatrix); + Vector3 vector = Vector3.Transform(input.ToVector3(), this.conversionMatrix); return new CieXyz(vector); } } diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbToRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbToRgbConverter.cs index ea5ef2bc11..d8cfa7c567 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbToRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/LinearRgbToRgbConverter.cs @@ -8,7 +8,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Color converter between and . /// - internal sealed class LinearRgbToRgbConverter + internal static class LinearRgbToRgbConverter { /// /// Performs the conversion from the input to an instance of type. @@ -16,13 +16,11 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result. [MethodImpl(InliningOptions.ShortMethod)] - public Rgb Convert(in LinearRgb input) - { - return new Rgb( + public static Rgb Convert(in LinearRgb input) => + new( r: input.WorkingSpace.Compress(input.R), g: input.WorkingSpace.Compress(input.G), b: input.WorkingSpace.Compress(input.B), workingSpace: input.WorkingSpace); - } } } diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/RgbToLinearRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/RgbToLinearRgbConverter.cs index 5ce09802c4..08a684baab 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/RgbToLinearRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/RgbToLinearRgbConverter.cs @@ -8,7 +8,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// /// Color converter between Rgb and LinearRgb. /// - internal class RgbToLinearRgbConverter + internal static class RgbToLinearRgbConverter { /// /// Performs the conversion from the input to an instance of type. @@ -16,13 +16,11 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result. [MethodImpl(InliningOptions.ShortMethod)] - public LinearRgb Convert(in Rgb input) - { - return new LinearRgb( + public static LinearRgb Convert(in Rgb input) + => new( r: input.WorkingSpace.Expand(input.R), g: input.WorkingSpace.Expand(input.G), b: input.WorkingSpace.Expand(input.B), workingSpace: input.WorkingSpace); - } } } diff --git a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/YCbCrAndRgbConverter.cs b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/YCbCrAndRgbConverter.cs index 727c89dd7a..ac4d857385 100644 --- a/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/YCbCrAndRgbConverter.cs +++ b/src/ImageSharp/ColorSpaces/Conversion/Implementation/Converters/YCbCrAndRgbConverter.cs @@ -11,9 +11,9 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// Color converter between and /// See for formulas. /// - internal sealed class YCbCrAndRgbConverter + internal static class YCbCrAndRgbConverter { - private static readonly Vector3 MaxBytes = new Vector3(255F); + private static readonly Vector3 MaxBytes = new(255F); /// /// Performs the conversion from the input to an instance of type. @@ -21,7 +21,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result. [MethodImpl(InliningOptions.ShortMethod)] - public Rgb Convert(in YCbCr input) + public static Rgb Convert(in YCbCr input) { float y = input.Y; float cb = input.Cb - 128F; @@ -40,7 +40,7 @@ namespace SixLabors.ImageSharp.ColorSpaces.Conversion /// The input color instance. /// The converted result. [MethodImpl(InliningOptions.ShortMethod)] - public YCbCr Convert(in Rgb input) + public static YCbCr Convert(in Rgb input) { Vector3 rgb = input.ToVector3() * MaxBytes; float r = rgb.X; diff --git a/src/ImageSharp/ColorSpaces/Hsl.cs b/src/ImageSharp/ColorSpaces/Hsl.cs index 98f9bdb7c2..01ea512a6d 100644 --- a/src/ImageSharp/ColorSpaces/Hsl.cs +++ b/src/ImageSharp/ColorSpaces/Hsl.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -13,25 +13,7 @@ namespace SixLabors.ImageSharp.ColorSpaces public readonly struct Hsl : IEquatable { private static readonly Vector3 Min = Vector3.Zero; - private static readonly Vector3 Max = new Vector3(360, 1, 1); - - /// - /// Gets the hue component. - /// A value ranging between 0 and 360. - /// - public readonly float H; - - /// - /// Gets the saturation component. - /// A value ranging between 0 and 1. - /// - public readonly float S; - - /// - /// Gets the lightness component. - /// A value ranging between 0 and 1. - /// - public readonly float L; + private static readonly Vector3 Max = new(360, 1, 1); /// /// Initializes a new instance of the struct. @@ -58,6 +40,24 @@ namespace SixLabors.ImageSharp.ColorSpaces this.L = vector.Z; } + /// + /// Gets the hue component. + /// A value ranging between 0 and 360. + /// + public readonly float H { get; } + + /// + /// Gets the saturation component. + /// A value ranging between 0 and 1. + /// + public readonly float S { get; } + + /// + /// Gets the lightness component. + /// A value ranging between 0 and 1. + /// + public readonly float L { get; } + /// /// Compares two objects for equality. /// @@ -95,10 +95,8 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(Hsl other) - { - return this.H.Equals(other.H) - && this.S.Equals(other.S) - && this.L.Equals(other.L); - } + => this.H.Equals(other.H) + && this.S.Equals(other.S) + && this.L.Equals(other.L); } } diff --git a/src/ImageSharp/ColorSpaces/Hsv.cs b/src/ImageSharp/ColorSpaces/Hsv.cs index a44aebbb17..284ef4e535 100644 --- a/src/ImageSharp/ColorSpaces/Hsv.cs +++ b/src/ImageSharp/ColorSpaces/Hsv.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -13,25 +13,7 @@ namespace SixLabors.ImageSharp.ColorSpaces public readonly struct Hsv : IEquatable { private static readonly Vector3 Min = Vector3.Zero; - private static readonly Vector3 Max = new Vector3(360, 1, 1); - - /// - /// Gets the hue component. - /// A value ranging between 0 and 360. - /// - public readonly float H; - - /// - /// Gets the saturation component. - /// A value ranging between 0 and 1. - /// - public readonly float S; - - /// - /// Gets the value (brightness) component. - /// A value ranging between 0 and 1. - /// - public readonly float V; + private static readonly Vector3 Max = new(360, 1, 1); /// /// Initializes a new instance of the struct. @@ -58,6 +40,24 @@ namespace SixLabors.ImageSharp.ColorSpaces this.V = vector.Z; } + /// + /// Gets the hue component. + /// A value ranging between 0 and 360. + /// + public readonly float H { get; } + + /// + /// Gets the saturation component. + /// A value ranging between 0 and 1. + /// + public readonly float S { get; } + + /// + /// Gets the value (brightness) component. + /// A value ranging between 0 and 1. + /// + public readonly float V { get; } + /// /// Compares two objects for equality. /// @@ -93,10 +93,8 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(Hsv other) - { - return this.H.Equals(other.H) - && this.S.Equals(other.S) - && this.V.Equals(other.V); - } + => this.H.Equals(other.H) + && this.S.Equals(other.S) + && this.V.Equals(other.V); } } diff --git a/src/ImageSharp/ColorSpaces/HunterLab.cs b/src/ImageSharp/ColorSpaces/HunterLab.cs index c3d808c6c3..4b5ea842d4 100644 --- a/src/ImageSharp/ColorSpaces/HunterLab.cs +++ b/src/ImageSharp/ColorSpaces/HunterLab.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -19,29 +19,6 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public static readonly CieXyz DefaultWhitePoint = Illuminants.C; - /// - /// Gets the lightness dimension. - /// A value usually ranging between 0 (black), 100 (diffuse white) or higher (specular white). - /// - public readonly float L; - - /// - /// Gets the a color component. - /// A value usually ranging from -100 to 100. Negative is green, positive magenta. - /// - public readonly float A; - - /// - /// Gets the b color component. - /// A value usually ranging from -100 to 100. Negative is blue, positive is yellow - /// - public readonly float B; - - /// - /// Gets the reference white point of this color. - /// - public readonly CieXyz WhitePoint; - /// /// Initializes a new instance of the struct. /// @@ -94,6 +71,29 @@ namespace SixLabors.ImageSharp.ColorSpaces this.WhitePoint = whitePoint; } + /// + /// Gets the lightness dimension. + /// A value usually ranging between 0 (black), 100 (diffuse white) or higher (specular white). + /// + public readonly float L { get; } + + /// + /// Gets the a color component. + /// A value usually ranging from -100 to 100. Negative is green, positive magenta. + /// + public readonly float A { get; } + + /// + /// Gets the b color component. + /// A value usually ranging from -100 to 100. Negative is blue, positive is yellow + /// + public readonly float B { get; } + + /// + /// Gets the reference white point of this color. + /// + public readonly CieXyz WhitePoint { get; } + /// /// Compares two objects for equality. /// @@ -128,11 +128,9 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(HunterLab other) - { - return this.L.Equals(other.L) - && this.A.Equals(other.A) - && this.B.Equals(other.B) - && this.WhitePoint.Equals(other.WhitePoint); - } + => this.L.Equals(other.L) + && this.A.Equals(other.A) + && this.B.Equals(other.B) + && this.WhitePoint.Equals(other.WhitePoint); } } diff --git a/src/ImageSharp/ColorSpaces/LinearRgb.cs b/src/ImageSharp/ColorSpaces/LinearRgb.cs index 5dffea678a..abf2c6e81a 100644 --- a/src/ImageSharp/ColorSpaces/LinearRgb.cs +++ b/src/ImageSharp/ColorSpaces/LinearRgb.cs @@ -21,29 +21,6 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public static readonly RgbWorkingSpace DefaultWorkingSpace = RgbWorkingSpaces.SRgb; - /// - /// Gets the red component. - /// A value usually ranging between 0 and 1. - /// - public readonly float R; - - /// - /// Gets the green component. - /// A value usually ranging between 0 and 1. - /// - public readonly float G; - - /// - /// Gets the blue component. - /// A value usually ranging between 0 and 1. - /// - public readonly float B; - - /// - /// Gets the LinearRgb color space - /// - public readonly RgbWorkingSpace WorkingSpace; - /// /// Initializes a new instance of the struct. /// @@ -95,6 +72,29 @@ namespace SixLabors.ImageSharp.ColorSpaces this.WorkingSpace = workingSpace; } + /// + /// Gets the red component. + /// A value usually ranging between 0 and 1. + /// + public readonly float R { get; } + + /// + /// Gets the green component. + /// A value usually ranging between 0 and 1. + /// + public readonly float G { get; } + + /// + /// Gets the blue component. + /// A value usually ranging between 0 and 1. + /// + public readonly float B { get; } + + /// + /// Gets the LinearRgb color space + /// + public readonly RgbWorkingSpace WorkingSpace { get; } + /// /// Compares two objects for equality. /// @@ -122,7 +122,7 @@ namespace SixLabors.ImageSharp.ColorSpaces /// /// The . [MethodImpl(InliningOptions.ShortMethod)] - public Vector3 ToVector3() => new Vector3(this.R, this.G, this.B); + public Vector3 ToVector3() => new(this.R, this.G, this.B); /// [MethodImpl(InliningOptions.ShortMethod)] @@ -137,10 +137,8 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(LinearRgb other) - { - return this.R.Equals(other.R) - && this.G.Equals(other.G) - && this.B.Equals(other.B); - } + => this.R.Equals(other.R) + && this.G.Equals(other.G) + && this.B.Equals(other.B); } } diff --git a/src/ImageSharp/ColorSpaces/Lms.cs b/src/ImageSharp/ColorSpaces/Lms.cs index 7ca8c3cf0f..ee77118909 100644 --- a/src/ImageSharp/ColorSpaces/Lms.cs +++ b/src/ImageSharp/ColorSpaces/Lms.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -14,24 +14,6 @@ namespace SixLabors.ImageSharp.ColorSpaces /// public readonly struct Lms : IEquatable { - /// - /// Gets the L long component. - /// A value usually ranging between -1 and 1. - /// - public readonly float L; - - /// - /// Gets the M medium component. - /// A value usually ranging between -1 and 1. - /// - public readonly float M; - - /// - /// Gets the S short component. - /// A value usually ranging between -1 and 1. - /// - public readonly float S; - /// /// Initializes a new instance of the struct. /// @@ -57,6 +39,24 @@ namespace SixLabors.ImageSharp.ColorSpaces this.S = vector.Z; } + /// + /// Gets the L long component. + /// A value usually ranging between -1 and 1. + /// + public readonly float L { get; } + + /// + /// Gets the M medium component. + /// A value usually ranging between -1 and 1. + /// + public readonly float M { get; } + + /// + /// Gets the S short component. + /// A value usually ranging between -1 and 1. + /// + public readonly float S { get; } + /// /// Compares two objects for equality. /// @@ -84,7 +84,7 @@ namespace SixLabors.ImageSharp.ColorSpaces /// /// The . [MethodImpl(InliningOptions.ShortMethod)] - public Vector3 ToVector3() => new Vector3(this.L, this.M, this.S); + public Vector3 ToVector3() => new(this.L, this.M, this.S); /// public override int GetHashCode() => HashCode.Combine(this.L, this.M, this.S); @@ -98,10 +98,8 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(Lms other) - { - return this.L.Equals(other.L) - && this.M.Equals(other.M) - && this.S.Equals(other.S); - } + => this.L.Equals(other.L) + && this.M.Equals(other.M) + && this.S.Equals(other.S); } } diff --git a/src/ImageSharp/ColorSpaces/Rgb.cs b/src/ImageSharp/ColorSpaces/Rgb.cs index 4902d98fd6..76d55d04d1 100644 --- a/src/ImageSharp/ColorSpaces/Rgb.cs +++ b/src/ImageSharp/ColorSpaces/Rgb.cs @@ -22,29 +22,6 @@ namespace SixLabors.ImageSharp.ColorSpaces private static readonly Vector3 Min = Vector3.Zero; private static readonly Vector3 Max = Vector3.One; - /// - /// Gets the red component. - /// A value usually ranging between 0 and 1. - /// - public readonly float R; - - /// - /// Gets the green component. - /// A value usually ranging between 0 and 1. - /// - public readonly float G; - - /// - /// Gets the blue component. - /// A value usually ranging between 0 and 1. - /// - public readonly float B; - - /// - /// Gets the Rgb color space - /// - public readonly RgbWorkingSpace WorkingSpace; - /// /// Initializes a new instance of the struct. /// @@ -95,6 +72,29 @@ namespace SixLabors.ImageSharp.ColorSpaces this.WorkingSpace = workingSpace; } + /// + /// Gets the red component. + /// A value usually ranging between 0 and 1. + /// + public readonly float R { get; } + + /// + /// Gets the green component. + /// A value usually ranging between 0 and 1. + /// + public readonly float G { get; } + + /// + /// Gets the blue component. + /// A value usually ranging between 0 and 1. + /// + public readonly float B { get; } + + /// + /// Gets the Rgb color space + /// + public readonly RgbWorkingSpace WorkingSpace { get; } + /// /// Allows the implicit conversion of an instance of to a /// . @@ -102,7 +102,7 @@ namespace SixLabors.ImageSharp.ColorSpaces /// The instance of to convert. /// An instance of . [MethodImpl(InliningOptions.ShortMethod)] - public static implicit operator Rgb(Rgb24 color) => new Rgb(color.R / 255F, color.G / 255F, color.B / 255F); + public static implicit operator Rgb(Rgb24 color) => new(color.R / 255F, color.G / 255F, color.B / 255F); /// /// Allows the implicit conversion of an instance of to a @@ -111,7 +111,7 @@ namespace SixLabors.ImageSharp.ColorSpaces /// The instance of to convert. /// An instance of . [MethodImpl(InliningOptions.ShortMethod)] - public static implicit operator Rgb(Rgba32 color) => new Rgb(color.R / 255F, color.G / 255F, color.B / 255F); + public static implicit operator Rgb(Rgba32 color) => new(color.R / 255F, color.G / 255F, color.B / 255F); /// /// Compares two objects for equality. @@ -144,7 +144,7 @@ namespace SixLabors.ImageSharp.ColorSpaces /// /// The . [MethodImpl(InliningOptions.ShortMethod)] - public Vector3 ToVector3() => new Vector3(this.R, this.G, this.B); + public Vector3 ToVector3() => new(this.R, this.G, this.B); /// public override int GetHashCode() => HashCode.Combine(this.R, this.G, this.B); @@ -158,10 +158,8 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(Rgb other) - { - return this.R.Equals(other.R) - && this.G.Equals(other.G) - && this.B.Equals(other.B); - } + => this.R.Equals(other.R) + && this.G.Equals(other.G) + && this.B.Equals(other.B); } } diff --git a/src/ImageSharp/ColorSpaces/YCbCr.cs b/src/ImageSharp/ColorSpaces/YCbCr.cs index cb4d7d091b..2670a27008 100644 --- a/src/ImageSharp/ColorSpaces/YCbCr.cs +++ b/src/ImageSharp/ColorSpaces/YCbCr.cs @@ -15,25 +15,7 @@ namespace SixLabors.ImageSharp.ColorSpaces public readonly struct YCbCr : IEquatable { private static readonly Vector3 Min = Vector3.Zero; - private static readonly Vector3 Max = new Vector3(255); - - /// - /// Gets the Y luminance component. - /// A value ranging between 0 and 255. - /// - public readonly float Y; - - /// - /// Gets the Cb chroma component. - /// A value ranging between 0 and 255. - /// - public readonly float Cb; - - /// - /// Gets the Cr chroma component. - /// A value ranging between 0 and 255. - /// - public readonly float Cr; + private static readonly Vector3 Max = new(255); /// /// Initializes a new instance of the struct. @@ -60,6 +42,24 @@ namespace SixLabors.ImageSharp.ColorSpaces this.Cr = vector.Z; } + /// + /// Gets the Y luminance component. + /// A value ranging between 0 and 255. + /// + public readonly float Y { get; } + + /// + /// Gets the Cb chroma component. + /// A value ranging between 0 and 255. + /// + public readonly float Cb { get; } + + /// + /// Gets the Cr chroma component. + /// A value ranging between 0 and 255. + /// + public readonly float Cr { get; } + /// /// Compares two objects for equality. /// @@ -94,10 +94,8 @@ namespace SixLabors.ImageSharp.ColorSpaces /// [MethodImpl(InliningOptions.ShortMethod)] public bool Equals(YCbCr other) - { - return this.Y.Equals(other.Y) - && this.Cb.Equals(other.Cb) - && this.Cr.Equals(other.Cr); - } + => this.Y.Equals(other.Y) + && this.Cb.Equals(other.Cb) + && this.Cr.Equals(other.Cr); } } diff --git a/src/ImageSharp/Diagnostics/MemoryDiagnostics.cs b/src/ImageSharp/Diagnostics/MemoryDiagnostics.cs index 33af606b9f..2cd286cd6f 100644 --- a/src/ImageSharp/Diagnostics/MemoryDiagnostics.cs +++ b/src/ImageSharp/Diagnostics/MemoryDiagnostics.cs @@ -9,6 +9,7 @@ namespace SixLabors.ImageSharp.Diagnostics /// /// Represents the method to handle . /// + /// The allocation stack trace. public delegate void UndisposedAllocationDelegate(string allocationStackTrace); /// diff --git a/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs b/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs index 7af2d9a362..4812b550d2 100644 --- a/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs +++ b/src/ImageSharp/Formats/Bmp/BmpDecoderCore.cs @@ -491,7 +491,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp int max = cmd[1]; int bytesToRead = (max + 1) / 2; - var run = new byte[bytesToRead]; + byte[] run = new byte[bytesToRead]; this.stream.Read(run, 0, run.Length); @@ -501,13 +501,11 @@ namespace SixLabors.ImageSharp.Formats.Bmp byte twoPixels = run[idx]; if (i % 2 == 0) { - byte leftPixel = (byte)((twoPixels >> 4) & 0xF); - buffer[count++] = leftPixel; + buffer[count++] = (byte)((twoPixels >> 4) & 0xF); } else { - byte rightPixel = (byte)(twoPixels & 0xF); - buffer[count++] = rightPixel; + buffer[count++] = (byte)(twoPixels & 0xF); idx++; } } @@ -597,7 +595,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp // Take this number of bytes from the stream as uncompressed data. int length = cmd[1]; - var run = new byte[length]; + byte[] run = new byte[length]; this.stream.Read(run, 0, run.Length); @@ -676,7 +674,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp // Take this number of bytes from the stream as uncompressed data. int length = cmd[1]; - var run = new byte[length * 3]; + byte[] run = new byte[length * 3]; this.stream.Read(run, 0, run.Length); @@ -909,7 +907,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp int r = (redMaskBits == 5) ? GetBytesFrom5BitValue((temp & redMask) >> rightShiftRedMask) : GetBytesFrom6BitValue((temp & redMask) >> rightShiftRedMask); int g = (greenMaskBits == 5) ? GetBytesFrom5BitValue((temp & greenMask) >> rightShiftGreenMask) : GetBytesFrom6BitValue((temp & greenMask) >> rightShiftGreenMask); int b = (blueMaskBits == 5) ? GetBytesFrom5BitValue((temp & blueMask) >> rightShiftBlueMask) : GetBytesFrom6BitValue((temp & blueMask) >> rightShiftBlueMask); - var rgb = new Rgb24((byte)r, (byte)g, (byte)b); + Rgb24 rgb = new((byte)r, (byte)g, (byte)b); color.FromRgb24(rgb); pixelRow[x] = color; @@ -1164,7 +1162,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp uint g = (uint)(temp & greenMask) >> rightShiftGreenMask; uint b = (uint)(temp & blueMask) >> rightShiftBlueMask; float alpha = alphaMask != 0 ? invMaxValueAlpha * ((uint)(temp & alphaMask) >> rightShiftAlphaMask) : 1.0f; - var vector4 = new Vector4( + Vector4 vector4 = new( r * invMaxValueRed, g * invMaxValueGreen, b * invMaxValueBlue, @@ -1246,7 +1244,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp this.stream.Read(buffer, 0, BmpInfoHeader.HeaderSizeSize); int headerSize = BinaryPrimitives.ReadInt32LittleEndian(buffer); - if (headerSize < BmpInfoHeader.CoreSize || headerSize > BmpInfoHeader.MaxHeaderSize) + if (headerSize is < BmpInfoHeader.CoreSize or > BmpInfoHeader.MaxHeaderSize) { BmpThrowHelper.ThrowNotSupportedException($"ImageSharp does not support this BMP file. HeaderSize is '{headerSize}'."); } @@ -1277,7 +1275,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp // color masks for each color channel follow the info header. if (this.infoHeader.Compression == BmpCompression.BitFields) { - var bitfieldsBuffer = new byte[12]; + byte[] bitfieldsBuffer = new byte[12]; this.stream.Read(bitfieldsBuffer, 0, 12); Span data = bitfieldsBuffer.AsSpan(); this.infoHeader.RedMask = BinaryPrimitives.ReadInt32LittleEndian(data[..4]); @@ -1286,7 +1284,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp } else if (this.infoHeader.Compression == BmpCompression.BI_ALPHABITFIELDS) { - var bitfieldsBuffer = new byte[16]; + byte[] bitfieldsBuffer = new byte[16]; this.stream.Read(bitfieldsBuffer, 0, 16); Span data = bitfieldsBuffer.AsSpan(); this.infoHeader.RedMask = BinaryPrimitives.ReadInt32LittleEndian(data[..4]); @@ -1396,6 +1394,9 @@ namespace SixLabors.ImageSharp.Formats.Bmp /// /// Reads the and from the stream and sets the corresponding fields. /// + /// The input stream. + /// Whether the image orientation is inverted. + /// The color palette. /// Bytes per color palette entry. Usually 4 bytes, but in case of Windows 2.x bitmaps or OS/2 1.x bitmaps /// the bytes per color palette entry's can be 3 bytes instead of 4. private int ReadImageHeaders(BufferedReadStream stream, out bool inverted, out byte[] palette) diff --git a/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs b/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs index dce6368c81..b216fd7a57 100644 --- a/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs +++ b/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs @@ -160,10 +160,10 @@ namespace SixLabors.ImageSharp.Formats.Bmp Span buffer = stackalloc byte[infoHeaderSize]; - this.WriteBitmapFileHeader(stream, infoHeaderSize, colorPaletteSize, iccProfileSize, infoHeader, buffer); + WriteBitmapFileHeader(stream, infoHeaderSize, colorPaletteSize, iccProfileSize, infoHeader, buffer); this.WriteBitmapInfoHeader(stream, infoHeader, buffer, infoHeaderSize); this.WriteImage(stream, image.Frames.RootFrame); - this.WriteColorProfile(stream, iccProfileData, buffer); + WriteColorProfile(stream, iccProfileData, buffer); stream.Flush(); } @@ -184,34 +184,33 @@ namespace SixLabors.ImageSharp.Formats.Bmp int hResolution = 0; int vResolution = 0; - if (metadata.ResolutionUnits != PixelResolutionUnit.AspectRatio) + if (metadata.ResolutionUnits != PixelResolutionUnit.AspectRatio + && metadata.HorizontalResolution > 0 + && metadata.VerticalResolution > 0) { - if (metadata.HorizontalResolution > 0 && metadata.VerticalResolution > 0) + switch (metadata.ResolutionUnits) { - switch (metadata.ResolutionUnits) - { - case PixelResolutionUnit.PixelsPerInch: + case PixelResolutionUnit.PixelsPerInch: - hResolution = (int)Math.Round(UnitConverter.InchToMeter(metadata.HorizontalResolution)); - vResolution = (int)Math.Round(UnitConverter.InchToMeter(metadata.VerticalResolution)); - break; + hResolution = (int)Math.Round(UnitConverter.InchToMeter(metadata.HorizontalResolution)); + vResolution = (int)Math.Round(UnitConverter.InchToMeter(metadata.VerticalResolution)); + break; - case PixelResolutionUnit.PixelsPerCentimeter: + case PixelResolutionUnit.PixelsPerCentimeter: - hResolution = (int)Math.Round(UnitConverter.CmToMeter(metadata.HorizontalResolution)); - vResolution = (int)Math.Round(UnitConverter.CmToMeter(metadata.VerticalResolution)); - break; + hResolution = (int)Math.Round(UnitConverter.CmToMeter(metadata.HorizontalResolution)); + vResolution = (int)Math.Round(UnitConverter.CmToMeter(metadata.VerticalResolution)); + break; - case PixelResolutionUnit.PixelsPerMeter: - hResolution = (int)Math.Round(metadata.HorizontalResolution); - vResolution = (int)Math.Round(metadata.VerticalResolution); + case PixelResolutionUnit.PixelsPerMeter: + hResolution = (int)Math.Round(metadata.HorizontalResolution); + vResolution = (int)Math.Round(metadata.VerticalResolution); - break; - } + break; } } - var infoHeader = new BmpInfoHeader( + BmpInfoHeader infoHeader = new( headerSize: infoHeaderSize, height: height, width: width, @@ -248,7 +247,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp /// The stream to write to. /// The color profile data. /// The buffer. - private void WriteColorProfile(Stream stream, byte[] iccProfileData, Span buffer) + private static void WriteColorProfile(Stream stream, byte[] iccProfileData, Span buffer) { if (iccProfileData != null) { @@ -270,9 +269,9 @@ namespace SixLabors.ImageSharp.Formats.Bmp /// The size in bytes of the color profile. /// The information header to write. /// The buffer to write to. - private void WriteBitmapFileHeader(Stream stream, int infoHeaderSize, int colorPaletteSize, int iccProfileSize, BmpInfoHeader infoHeader, Span buffer) + private static void WriteBitmapFileHeader(Stream stream, int infoHeaderSize, int colorPaletteSize, int iccProfileSize, BmpInfoHeader infoHeader, Span buffer) { - var fileHeader = new BmpFileHeader( + BmpFileHeader fileHeader = new( type: BmpConstants.TypeMarkers.Bitmap, fileSize: BmpFileHeader.Size + infoHeaderSize + colorPaletteSize + iccProfileSize + infoHeader.ImageSize, reserved: 0, @@ -555,7 +554,7 @@ namespace SixLabors.ImageSharp.Formats.Bmp if (pixelRowSpan.Length % 2 != 0) { - stream.WriteByte((byte)((pixelRowSpan[pixelRowSpan.Length - 1] << 4) | 0)); + stream.WriteByte((byte)((pixelRowSpan[^1] << 4) | 0)); } for (int i = 0; i < rowPadding; i++) diff --git a/src/ImageSharp/Formats/Bmp/BmpInfoHeader.cs b/src/ImageSharp/Formats/Bmp/BmpInfoHeader.cs index 9c0efcb6d3..e7536ccac6 100644 --- a/src/ImageSharp/Formats/Bmp/BmpInfoHeader.cs +++ b/src/ImageSharp/Formats/Bmp/BmpInfoHeader.cs @@ -382,18 +382,16 @@ namespace SixLabors.ImageSharp.Formats.Bmp /// public static BmpInfoHeader ParseOs2Version2(ReadOnlySpan data) { - var infoHeader = new BmpInfoHeader( + BmpInfoHeader infoHeader = new( headerSize: BinaryPrimitives.ReadInt32LittleEndian(data[..4]), width: BinaryPrimitives.ReadInt32LittleEndian(data.Slice(4, 4)), height: BinaryPrimitives.ReadInt32LittleEndian(data.Slice(8, 4)), planes: BinaryPrimitives.ReadInt16LittleEndian(data.Slice(12, 2)), bitsPerPixel: BinaryPrimitives.ReadInt16LittleEndian(data.Slice(14, 2))); - int compression = BinaryPrimitives.ReadInt32LittleEndian(data.Slice(16, 4)); - // The compression value in OS/2 bitmap has a different meaning than in windows bitmaps. // Map the OS/2 value to the windows values. - switch (compression) + switch (BinaryPrimitives.ReadInt32LittleEndian(data.Slice(16, 4))) { case 0: infoHeader.Compression = BmpCompression.RGB; @@ -465,11 +463,12 @@ namespace SixLabors.ImageSharp.Formats.Bmp /// The data to parse. /// The parsed header. /// + /// Invalid size. public static BmpInfoHeader ParseV5(ReadOnlySpan data) { if (data.Length < SizeV5) { - throw new ArgumentException(nameof(data), $"Must be {SizeV5} bytes. Was {data.Length} bytes."); + throw new ArgumentException($"Must be {SizeV5} bytes. Was {data.Length} bytes.", nameof(data)); } return MemoryMarshal.Cast(data)[0]; @@ -545,13 +544,13 @@ namespace SixLabors.ImageSharp.Formats.Bmp internal void VerifyDimensions() { - const int MaximumBmpDimension = 65535; + const int maximumBmpDimension = 65535; - if (this.Width > MaximumBmpDimension || this.Height > MaximumBmpDimension) + if (this.Width > maximumBmpDimension || this.Height > maximumBmpDimension) { throw new InvalidOperationException( $"The input bmp '{this.Width}x{this.Height}' is " - + $"bigger then the max allowed size '{MaximumBmpDimension}x{MaximumBmpDimension}'"); + + $"bigger then the max allowed size '{maximumBmpDimension}x{maximumBmpDimension}'"); } } } diff --git a/src/ImageSharp/Formats/DecoderOptions.cs b/src/ImageSharp/Formats/DecoderOptions.cs index 8f16c6ecc7..e21f21f7b2 100644 --- a/src/ImageSharp/Formats/DecoderOptions.cs +++ b/src/ImageSharp/Formats/DecoderOptions.cs @@ -29,7 +29,7 @@ namespace SixLabors.ImageSharp.Formats /// /// Gets or sets the target size to decode the image into. /// - public Size? TargetSize { get; set; } = null; + public Size? TargetSize { get; set; } /// /// Gets or sets the sampler to use when resizing during decoding. @@ -39,7 +39,7 @@ namespace SixLabors.ImageSharp.Formats /// /// Gets or sets a value indicating whether to ignore encoded metadata when decoding. /// - public bool SkipMetadata { get; set; } = false; + public bool SkipMetadata { get; set; } /// /// Gets or sets the maximum number of image frames to decode, inclusive. diff --git a/src/ImageSharp/Formats/Gif/GifEncoderCore.cs b/src/ImageSharp/Formats/Gif/GifEncoderCore.cs index 0f7606a432..f354e42f32 100644 --- a/src/ImageSharp/Formats/Gif/GifEncoderCore.cs +++ b/src/ImageSharp/Formats/Gif/GifEncoderCore.cs @@ -108,10 +108,10 @@ namespace SixLabors.ImageSharp.Formats.Gif this.bitDepth = ColorNumerics.GetBitsNeededForColorDepth(quantized.Palette.Length); // Write the header. - this.WriteHeader(stream); + WriteHeader(stream); // Write the LSD. - int index = this.GetTransparentIndex(quantized); + int index = GetTransparentIndex(quantized); this.WriteLogicalScreenDescriptor(metadata, image.Width, image.Height, index, useGlobalTable, stream); if (useGlobalTable) @@ -193,7 +193,7 @@ namespace SixLabors.ImageSharp.Formats.Gif if (previousFrame != null && previousMeta.ColorTableLength != frameMetadata.ColorTableLength && frameMetadata.ColorTableLength > 0) { - var options = new QuantizerOptions + QuantizerOptions options = new() { Dither = this.quantizer.Options.Dither, DitherScale = this.quantizer.Options.DitherScale, @@ -211,7 +211,7 @@ namespace SixLabors.ImageSharp.Formats.Gif } this.bitDepth = ColorNumerics.GetBitsNeededForColorDepth(quantized.Palette.Length); - this.WriteGraphicalControlExtension(frameMetadata, this.GetTransparentIndex(quantized), stream); + this.WriteGraphicalControlExtension(frameMetadata, GetTransparentIndex(quantized), stream); this.WriteImageDescriptor(frame, true, stream); this.WriteColorTable(quantized, stream); this.WriteImageData(quantized, stream); @@ -231,7 +231,7 @@ namespace SixLabors.ImageSharp.Formats.Gif /// /// The . /// - private int GetTransparentIndex(IndexedImageFrame quantized) + private static int GetTransparentIndex(IndexedImageFrame quantized) where TPixel : unmanaged, IPixel { // Transparent pixels are much more likely to be found at the end of a palette. @@ -259,7 +259,7 @@ namespace SixLabors.ImageSharp.Formats.Gif /// /// The stream to write to. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void WriteHeader(Stream stream) => stream.Write(GifConstants.MagicNumber); + private static void WriteHeader(Stream stream) => stream.Write(GifConstants.MagicNumber); /// /// Writes the logical screen descriptor to the stream. @@ -308,7 +308,7 @@ namespace SixLabors.ImageSharp.Formats.Gif } } - var descriptor = new GifLogicalScreenDescriptor( + GifLogicalScreenDescriptor descriptor = new( width: (ushort)width, height: (ushort)height, packed: packedValue, @@ -332,14 +332,14 @@ namespace SixLabors.ImageSharp.Formats.Gif // Application Extension: Loop repeat count. if (frameCount > 1 && repeatCount != 1) { - var loopingExtension = new GifNetscapeLoopingApplicationExtension(repeatCount); + GifNetscapeLoopingApplicationExtension loopingExtension = new(repeatCount); this.WriteExtension(loopingExtension, stream); } // Application Extension: XMP Profile. if (xmpProfile != null) { - var xmpExtension = new GifXmpApplicationExtension(xmpProfile.Data); + GifXmpApplicationExtension xmpExtension = new(xmpProfile.Data); this.WriteExtension(xmpExtension, stream); } } @@ -411,7 +411,7 @@ namespace SixLabors.ImageSharp.Formats.Gif disposalMethod: metadata.DisposalMethod, transparencyFlag: transparencyIndex > -1); - var extension = new GifGraphicControlExtension( + GifGraphicControlExtension extension = new( packed: packedValue, delayTime: (ushort)metadata.FrameDelay, transparencyIndex: unchecked((byte)transparencyIndex)); @@ -422,6 +422,7 @@ namespace SixLabors.ImageSharp.Formats.Gif /// /// Writes the provided extension to the stream. /// + /// The type of gif extension. /// The extension to write to the stream. /// The stream to write to. private void WriteExtension(TGifExtension extension, Stream stream) @@ -472,7 +473,7 @@ namespace SixLabors.ImageSharp.Formats.Gif sortFlag: false, localColorTableSize: this.bitDepth - 1); - var descriptor = new GifImageDescriptor( + GifImageDescriptor descriptor = new( left: 0, top: 0, width: (ushort)image.Width, @@ -517,7 +518,7 @@ namespace SixLabors.ImageSharp.Formats.Gif private void WriteImageData(IndexedImageFrame image, Stream stream) where TPixel : unmanaged, IPixel { - using var encoder = new LzwEncoder(this.memoryAllocator, (byte)this.bitDepth); + using LzwEncoder encoder = new(this.memoryAllocator, (byte)this.bitDepth); encoder.Encode(((IPixelSource)image).PixelBuffer, stream); } } diff --git a/src/ImageSharp/Formats/Jpeg/Components/Block8x8F.cs b/src/ImageSharp/Formats/Jpeg/Components/Block8x8F.cs index 7d71730d15..16d95f99f6 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Block8x8F.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Block8x8F.cs @@ -161,7 +161,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components { if (Avx.IsSupported) { - var valueVec = Vector256.Create(value); + Vector256 valueVec = Vector256.Create(value); this.V0 = Avx.Multiply(this.V0, valueVec); this.V1 = Avx.Multiply(this.V1, valueVec); this.V2 = Avx.Multiply(this.V2, valueVec); @@ -173,7 +173,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components } else { - var valueVec = new Vector4(value); + Vector4 valueVec = new(value); this.V0L *= valueVec; this.V0R *= valueVec; this.V1L *= valueVec; @@ -196,6 +196,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// /// Multiply all elements of the block by the corresponding elements of 'other'. /// + /// The other block. [MethodImpl(InliningOptions.ShortMethod)] public unsafe void MultiplyInPlace(ref Block8x8F other) { @@ -240,7 +241,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components { if (Avx.IsSupported) { - var valueVec = Vector256.Create(value); + Vector256 valueVec = Vector256.Create(value); this.V0 = Avx.Add(this.V0, valueVec); this.V1 = Avx.Add(this.V1, valueVec); this.V2 = Avx.Add(this.V2, valueVec); @@ -252,7 +253,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components } else { - var valueVec = new Vector4(value); + Vector4 valueVec = new(value); this.V0L += valueVec; this.V0R += valueVec; this.V1L += valueVec; @@ -330,6 +331,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// /// Level shift by +maximum/2, clip to [0..maximum], and round all the values in the block. /// + /// The maximum value. public void NormalizeColorsAndRoundInPlace(float maximum) { if (SimdUtils.HasVector8) @@ -421,7 +423,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components { const int equalityMask = unchecked((int)0b1111_1111_1111_1111_1111_1111_1111_1111); - var targetVector = Vector256.Create(value); + Vector256 targetVector = Vector256.Create(value); ref Vector256 blockStride = ref this.V0; for (int i = 0; i < RowCount; i++) @@ -468,20 +470,46 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components && this.V7L == other.V7L && this.V7R == other.V7R; + /// + public override bool Equals(object obj) => this.Equals((Block8x8F)obj); + + /// + public override int GetHashCode() + { + int left = HashCode.Combine( + this.V0L, + this.V1L, + this.V2L, + this.V3L, + this.V4L, + this.V5L, + this.V6L, + this.V7L); + + int right = HashCode.Combine( + this.V0R, + this.V1R, + this.V2R, + this.V3R, + this.V4R, + this.V5R, + this.V6R, + this.V7R); + + return HashCode.Combine(left, right); + } + /// public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append('['); for (int i = 0; i < Size - 1; i++) { - sb.Append(this[i]); - sb.Append(','); + sb.Append(this[i]).Append(','); } - sb.Append(this[Size - 1]); - - sb.Append(']'); + sb.Append(this[Size - 1]).Append(']'); return sb.ToString(); } diff --git a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverterBase.cs b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverterBase.cs index c2e01df998..c159ed7d21 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverterBase.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverterBase.cs @@ -20,6 +20,8 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// /// Initializes a new instance of the class. /// + /// The color space. + /// The precision in bits. protected JpegColorConverterBase(JpegColorSpace colorSpace, int precision) { this.ColorSpace = colorSpace; @@ -66,6 +68,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// /// Returns the corresponding to the given /// + /// The color space. + /// The precision in bits. + /// Invalid colorspace. public static JpegColorConverterBase GetConverter(JpegColorSpace colorSpace, int precision) { JpegColorConverterBase converter = Array.Find( @@ -75,7 +80,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components if (converter is null) { - throw new Exception($"Could not find any converter for JpegColorSpace {colorSpace}!"); + throw new InvalidImageContentException($"Could not find any converter for JpegColorSpace {colorSpace}!"); } return converter; @@ -104,7 +109,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components // 5 color types with 2 supported precisions: 8 bit & 12 bit const int colorConvertersCount = 5 * 2; - var converters = new JpegColorConverterBase[colorConvertersCount]; + JpegColorConverterBase[] converters = new JpegColorConverterBase[colorConvertersCount]; // 8-bit converters converters[0] = GetYCbCrConverter(8); @@ -126,6 +131,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// /// Returns the s for the YCbCr colorspace. /// + /// The precision in bits. private static JpegColorConverterBase GetYCbCrConverter(int precision) { if (JpegColorConverterAvx.IsSupported) @@ -144,6 +150,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// /// Returns the s for the YccK colorspace. /// + /// The precision in bits. private static JpegColorConverterBase GetYccKConverter(int precision) { if (JpegColorConverterAvx.IsSupported) @@ -162,6 +169,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// /// Returns the s for the CMYK colorspace. /// + /// The precision in bits. private static JpegColorConverterBase GetCmykConverter(int precision) { if (JpegColorConverterAvx.IsSupported) @@ -180,6 +188,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// /// Returns the s for the gray scale colorspace. /// + /// The precision in bits. private static JpegColorConverterBase GetGrayScaleConverter(int precision) { if (JpegColorConverterAvx.IsSupported) @@ -198,6 +207,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// /// Returns the s for the RGB colorspace. /// + /// The precision in bits. private static JpegColorConverterBase GetRgbConverter(int precision) { if (JpegColorConverterAvx.IsSupported) diff --git a/src/ImageSharp/Formats/Jpeg/Components/Decoder/ArithmeticScanDecoder.cs b/src/ImageSharp/Formats/Jpeg/Components/Decoder/ArithmeticScanDecoder.cs index ae97c7e54a..21727bc99c 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Decoder/ArithmeticScanDecoder.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Decoder/ArithmeticScanDecoder.cs @@ -225,10 +225,10 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder { for (int i = 0; i < this.components.Length; i++) { - var component = this.components[i] as ArithmeticDecodingComponent; - this.dcDecodingTables[i] = this.GetArithmeticTable(arithmeticDecodingTables, true, component.DcTableId); + ArithmeticDecodingComponent component = this.components[i] as ArithmeticDecodingComponent; + this.dcDecodingTables[i] = GetArithmeticTable(arithmeticDecodingTables, true, component.DcTableId); component.DcStatistics = this.CreateOrGetStatisticsBin(true, component.DcTableId); - this.acDecodingTables[i] = this.GetArithmeticTable(arithmeticDecodingTables, false, component.AcTableId); + this.acDecodingTables[i] = GetArithmeticTable(arithmeticDecodingTables, false, component.AcTableId); component.AcStatistics = this.CreateOrGetStatisticsBin(false, component.AcTableId); } } @@ -276,7 +276,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder this.spectralConverter.InjectFrameData(frame, jpegData); } - private ArithmeticDecodingTable GetArithmeticTable(List arithmeticDecodingTables, bool isDcTable, int identifier) + private static ArithmeticDecodingTable GetArithmeticTable(List arithmeticDecodingTables, bool isDcTable, int identifier) { int tableClass = isDcTable ? 0 : 1; @@ -306,15 +306,16 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder } } - var statistic = new ArithmeticStatistics(dc, identifier); + ArithmeticStatistics statistic = new(dc, identifier); this.statistics.Add(statistic); return statistic; } private void ParseBaselineData() { - foreach (ArithmeticDecodingComponent component in this.components) + for (int i = 0; i < this.components.Length; i++) { + ArithmeticDecodingComponent component = (ArithmeticDecodingComponent)this.components[i]; component.DcPredictor = 0; component.DcContext = 0; component.DcStatistics?.Reset(); @@ -441,7 +442,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder for (int k = 0; k < this.scanComponentCount; k++) { int order = this.frame.ComponentOrder[k]; - var component = this.components[order] as ArithmeticDecodingComponent; + ArithmeticDecodingComponent component = this.components[order] as ArithmeticDecodingComponent; ref ArithmeticDecodingTable dcDecodingTable = ref this.dcDecodingTables[component.DcTableId]; ref ArithmeticDecodingTable acDecodingTable = ref this.acDecodingTables[component.AcTableId]; @@ -491,7 +492,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder private void ParseBaselineDataSingleComponent() { - var component = this.frame.Components[0] as ArithmeticDecodingComponent; + ArithmeticDecodingComponent component = this.frame.Components[0] as ArithmeticDecodingComponent; int mcuLines = this.frame.McusPerColumn; int w = component.WidthInBlocks; int h = component.SamplingFactors.Height; @@ -537,7 +538,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder private void ParseBaselineDataNonInterleaved() { - var component = (ArithmeticDecodingComponent)this.components[this.frame.ComponentOrder[0]]; + ArithmeticDecodingComponent component = (ArithmeticDecodingComponent)this.components[this.frame.ComponentOrder[0]]; ref JpegBitReader reader = ref this.scanBuffer; int w = component.WidthInBlocks; @@ -586,7 +587,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder for (int k = 0; k < this.scanComponentCount; k++) { int order = this.frame.ComponentOrder[k]; - var component = this.components[order] as ArithmeticDecodingComponent; + ArithmeticDecodingComponent component = this.components[order] as ArithmeticDecodingComponent; ref ArithmeticDecodingTable dcDecodingTable = ref this.dcDecodingTables[component.DcTableId]; int h = component.HorizontalSamplingFactor; @@ -628,7 +629,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder private void ParseProgressiveDataNonInterleaved() { - var component = this.components[this.frame.ComponentOrder[0]] as ArithmeticDecodingComponent; + ArithmeticDecodingComponent component = this.components[this.frame.ComponentOrder[0]] as ArithmeticDecodingComponent; ref JpegBitReader reader = ref this.scanBuffer; int w = component.WidthInBlocks; @@ -1140,7 +1141,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder { for (int i = 0; i < this.components.Length; i++) { - var component = this.components[i] as ArithmeticDecodingComponent; + ArithmeticDecodingComponent component = this.components[i] as ArithmeticDecodingComponent; component.DcPredictor = 0; } diff --git a/src/ImageSharp/Formats/Jpeg/Components/Decoder/JpegFileMarker.cs b/src/ImageSharp/Formats/Jpeg/Components/Decoder/JpegFileMarker.cs index f3ceb3584a..185e5b06b0 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Decoder/JpegFileMarker.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Decoder/JpegFileMarker.cs @@ -1,6 +1,7 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. +using System.Globalization; using System.Runtime.CompilerServices; namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder @@ -62,8 +63,6 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder /// public override string ToString() - { - return this.Marker.ToString("X"); - } + => this.Marker.ToString("X", CultureInfo.InvariantCulture); } } diff --git a/src/ImageSharp/Formats/Jpeg/Components/Encoder/EncodingConfigs/JpegFrameConfig.cs b/src/ImageSharp/Formats/Jpeg/Components/Encoder/EncodingConfigs/JpegFrameConfig.cs index 18afff7383..feb1ae8eef 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Encoder/EncodingConfigs/JpegFrameConfig.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Encoder/EncodingConfigs/JpegFrameConfig.cs @@ -39,6 +39,6 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Encoder public int MaxVerticalSamplingFactor { get; } - public byte? AdobeColorTransformMarkerFlag { get; set; } = null; + public byte? AdobeColorTransformMarkerFlag { get; set; } } } diff --git a/src/ImageSharp/Formats/Jpeg/Components/Encoder/HuffmanSpec.cs b/src/ImageSharp/Formats/Jpeg/Components/Encoder/HuffmanSpec.cs index 97f051c76c..1a262f480d 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Encoder/HuffmanSpec.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Encoder/HuffmanSpec.cs @@ -122,16 +122,6 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Encoder 0xf9, 0xfa }); - /// - /// Gets count[i] - The number of codes of length i bits. - /// - public readonly byte[] Count; - - /// - /// Gets value[i] - The decoded value of the codeword at the given index. - /// - public readonly byte[] Values; - /// /// Initializes a new instance of the struct. /// @@ -146,5 +136,15 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Encoder this.Count = count; this.Values = values; } + + /// + /// Gets the count[i] - The number of codes of length i bits. + /// + public readonly byte[] Count { get; } + + /// + /// Gets the value[i] - The decoded value of the codeword at the given index. + /// + public readonly byte[] Values { get; } } } diff --git a/src/ImageSharp/Formats/Jpeg/Components/RowOctet.cs b/src/ImageSharp/Formats/Jpeg/Components/RowOctet.cs index c899cf3adb..5872d47678 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/RowOctet.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/RowOctet.cs @@ -11,6 +11,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components /// /// Cache 8 pixel rows on the stack, which may originate from different buffers of a . /// + /// The type of element in each row. [StructLayout(LayoutKind.Sequential)] internal ref struct RowOctet where T : struct @@ -92,6 +93,8 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components [MethodImpl(MethodImplOptions.NoInlining)] private static Span ThrowIndexOutOfRangeException() +#pragma warning disable CA2201 // Do not raise reserved exception types => throw new IndexOutOfRangeException(); +#pragma warning restore CA2201 // Do not raise reserved exception types } } diff --git a/src/ImageSharp/Formats/Jpeg/JpegDecoderCore.cs b/src/ImageSharp/Formats/Jpeg/JpegDecoderCore.cs index 242e61e604..3d65021a77 100644 --- a/src/ImageSharp/Formats/Jpeg/JpegDecoderCore.cs +++ b/src/ImageSharp/Formats/Jpeg/JpegDecoderCore.cs @@ -213,7 +213,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg public Image Decode(BufferedReadStream stream, CancellationToken cancellationToken) where TPixel : unmanaged, IPixel { - using var spectralConverter = new SpectralConverter(this.configuration, this.resizeMode == JpegDecoderResizeMode.ScaleOnly ? null : this.Options.TargetSize); + using SpectralConverter spectralConverter = new(this.configuration, this.resizeMode == JpegDecoderResizeMode.ScaleOnly ? null : this.Options.TargetSize); this.ParseStream(stream, spectralConverter, cancellationToken); this.InitExifProfile(); this.InitIccProfile(); @@ -257,12 +257,12 @@ namespace SixLabors.ImageSharp.Formats.Jpeg JpegThrowHelper.ThrowInvalidImageContentException("Not enough data to read marker"); } - using var ms = new MemoryStream(tableBytes); - using var stream = new BufferedReadStream(this.configuration, ms); + using MemoryStream ms = new(tableBytes); + using BufferedReadStream stream = new(this.configuration, ms); // Check for the Start Of Image marker. int bytesRead = stream.Read(this.markerBuffer, 0, 2); - var fileMarker = new JpegFileMarker(this.markerBuffer[1], 0); + JpegFileMarker fileMarker = new(this.markerBuffer[1], 0); if (fileMarker.Marker != JpegConstants.Markers.SOI) { JpegThrowHelper.ThrowInvalidImageContentException("Missing SOI marker."); @@ -290,7 +290,6 @@ namespace SixLabors.ImageSharp.Formats.Jpeg switch (fileMarker.Marker) { case JpegConstants.Markers.SOI: - break; case JpegConstants.Markers.RST0: case JpegConstants.Markers.RST7: break; @@ -335,7 +334,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg // Check for the Start Of Image marker. stream.Read(this.markerBuffer, 0, 2); - var fileMarker = new JpegFileMarker(this.markerBuffer[1], 0); + JpegFileMarker fileMarker = new(this.markerBuffer[1], 0); if (fileMarker.Marker != JpegConstants.Markers.SOI) { JpegThrowHelper.ThrowInvalidImageContentException("Missing SOI marker."); @@ -409,12 +408,10 @@ namespace SixLabors.ImageSharp.Formats.Jpeg this.ProcessStartOfScanMarker(stream, markerContentByteSize); break; } - else - { - // It's highly unlikely that APPn related data will be found after the SOS marker - // We should have gathered everything we need by now. - return; - } + + // It's highly unlikely that APPn related data will be found after the SOS marker + // We should have gathered everything we need by now. + return; case JpegConstants.Markers.DHT: @@ -654,7 +651,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg { if (this.hasIcc) { - var profile = new IccProfile(this.iccData); + IccProfile profile = new(this.iccData); if (profile.CheckIsValid()) { this.Metadata.IccProfile = profile; @@ -669,8 +666,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg { if (this.hasIptc) { - var profile = new IptcProfile(this.iptcData); - this.Metadata.IptcProfile = profile; + this.Metadata.IptcProfile = new IptcProfile(this.iptcData); } } @@ -681,8 +677,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg { if (this.hasXmp) { - var profile = new XmpProfile(this.xmpData); - this.Metadata.XmpProfile = profile; + this.Metadata.XmpProfile = new XmpProfile(this.xmpData); } } @@ -723,7 +718,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg /// /// The profile data array. /// The array containing addition profile data. - private void ExtendProfile(ref byte[] profile, byte[] extension) + private static void ExtendProfile(ref byte[] profile, byte[] extension) { int currentLength = profile.Length; @@ -751,7 +746,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg stream.Read(this.temp, 0, JFifMarker.Length); remaining -= JFifMarker.Length; - JFifMarker.TryParse(this.temp, out this.jFif); + _ = JFifMarker.TryParse(this.temp, out this.jFif); // TODO: thumbnail if (remaining > 0) @@ -772,9 +767,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg /// The remaining bytes in the segment block. private void ProcessApp1Marker(BufferedReadStream stream, int remaining) { - const int ExifMarkerLength = 6; - const int XmpMarkerLength = 29; - if (remaining < ExifMarkerLength || this.skipMetadata) + const int exifMarkerLength = 6; + const int xmpMarkerLength = 29; + if (remaining < exifMarkerLength || this.skipMetadata) { // Skip the application header length. stream.Skip(remaining); @@ -787,8 +782,8 @@ namespace SixLabors.ImageSharp.Formats.Jpeg } // XMP marker is the longer then the EXIF marker, so first try read the EXIF marker bytes. - stream.Read(this.temp, 0, ExifMarkerLength); - remaining -= ExifMarkerLength; + stream.Read(this.temp, 0, exifMarkerLength); + remaining -= exifMarkerLength; if (ProfileResolver.IsProfile(this.temp, ProfileResolver.ExifMarker)) { @@ -803,15 +798,15 @@ namespace SixLabors.ImageSharp.Formats.Jpeg else { // If the EXIF information exceeds 64K, it will be split over multiple APP1 markers. - this.ExtendProfile(ref this.exifData, profile); + ExtendProfile(ref this.exifData, profile); } remaining = 0; } - if (ProfileResolver.IsProfile(this.temp, ProfileResolver.XmpMarker[..ExifMarkerLength])) + if (ProfileResolver.IsProfile(this.temp, ProfileResolver.XmpMarker[..exifMarkerLength])) { - const int remainingXmpMarkerBytes = XmpMarkerLength - ExifMarkerLength; + const int remainingXmpMarkerBytes = xmpMarkerLength - exifMarkerLength; if (remaining < remainingXmpMarkerBytes || this.skipMetadata) { // Skip the application header length. @@ -819,7 +814,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg return; } - stream.Read(this.temp, ExifMarkerLength, remainingXmpMarkerBytes); + stream.Read(this.temp, exifMarkerLength, remainingXmpMarkerBytes); remaining -= remainingXmpMarkerBytes; if (ProfileResolver.IsProfile(this.temp, ProfileResolver.XmpMarker)) { @@ -834,7 +829,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg else { // If the XMP information exceeds 64K, it will be split over multiple APP1 markers. - this.ExtendProfile(ref this.xmpData, profile); + ExtendProfile(ref this.xmpData, profile); } remaining = 0; @@ -853,16 +848,16 @@ namespace SixLabors.ImageSharp.Formats.Jpeg private void ProcessApp2Marker(BufferedReadStream stream, int remaining) { // Length is 14 though we only need to check 12. - const int Icclength = 14; - if (remaining < Icclength || this.skipMetadata) + const int icclength = 14; + if (remaining < icclength || this.skipMetadata) { stream.Skip(remaining); return; } - byte[] identifier = new byte[Icclength]; - stream.Read(identifier, 0, Icclength); - remaining -= Icclength; // We have read it by this point + byte[] identifier = new byte[icclength]; + stream.Read(identifier, 0, icclength); + remaining -= icclength; // We have read it by this point if (ProfileResolver.IsProfile(identifier, ProfileResolver.IccMarker)) { @@ -877,7 +872,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg else { // If the ICC information exceeds 64K, it will be split over multiple APP2 markers - this.ExtendProfile(ref this.iccData, profile); + ExtendProfile(ref this.iccData, profile); } } else @@ -971,7 +966,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg byte conditioningTableValue = (byte)stream.ReadByte(); remaining--; - var arithmeticTable = new ArithmeticDecodingTable(tableClass, identifier); + ArithmeticDecodingTable arithmeticTable = new(tableClass, identifier); arithmeticTable.Configure(conditioningTableValue); bool tableEntryReplaced = false; @@ -1029,16 +1024,16 @@ namespace SixLabors.ImageSharp.Formats.Jpeg /// The remaining bytes in the segment block. private void ProcessApp14Marker(BufferedReadStream stream, int remaining) { - const int MarkerLength = AdobeMarker.Length; - if (remaining < MarkerLength) + const int markerLength = AdobeMarker.Length; + if (remaining < markerLength) { // Skip the application header length stream.Skip(remaining); return; } - stream.Read(this.temp, 0, MarkerLength); - remaining -= MarkerLength; + stream.Read(this.temp, 0, markerLength); + remaining -= markerLength; if (AdobeMarker.TryParse(this.temp, out this.adobe)) { @@ -1086,7 +1081,6 @@ namespace SixLabors.ImageSharp.Formats.Jpeg { // 8 bit values case 0: - { // Validate: 8 bit table needs exactly 64 bytes if (remaining < 64) { @@ -1103,11 +1097,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg } break; - } // 16 bit values case 1: - { // Validate: 16 bit table needs exactly 128 bytes if (remaining < 128) { @@ -1124,14 +1116,11 @@ namespace SixLabors.ImageSharp.Formats.Jpeg } break; - } // Unknown precision - error default: - { JpegThrowHelper.ThrowBadQuantizationTablePrecision(tablePrecision); break; - } } // Estimating quality @@ -1139,17 +1128,13 @@ namespace SixLabors.ImageSharp.Formats.Jpeg { // luminance table case 0: - { jpegMetadata.LuminanceQuality = Quantization.EstimateLuminanceQuality(ref table); break; - } // chrominance table case 1: - { jpegMetadata.ChrominanceQuality = Quantization.EstimateChrominanceQuality(ref table); break; - } } } } @@ -1312,7 +1297,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg const int codeValuesMaxByteSize = 256; const int totalBufferSize = codeLengthsByteSize + codeValuesMaxByteSize + HuffmanTable.WorkspaceByteSize; - var huffmanScanDecoder = this.scanDecoder as HuffmanScanDecoder; + HuffmanScanDecoder huffmanScanDecoder = this.scanDecoder as HuffmanScanDecoder; if (huffmanScanDecoder is null) { JpegThrowHelper.ThrowInvalidImageContentException("missing huffman table data"); @@ -1399,6 +1384,8 @@ namespace SixLabors.ImageSharp.Formats.Jpeg /// /// Processes the SOS (Start of scan marker). /// + /// The input stream. + /// The remaining bytes in the segment block. private void ProcessStartOfScanMarker(BufferedReadStream stream, int remaining) { if (this.Frame is null) @@ -1479,11 +1466,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg JpegThrowHelper.ThrowInvalidImageContentException("Not enough data to read progressive scan decoding data"); } - int spectralStart = this.temp[0]; - this.scanDecoder.SpectralStart = spectralStart; + this.scanDecoder.SpectralStart = this.temp[0]; - int spectralEnd = this.temp[1]; - this.scanDecoder.SpectralEnd = spectralEnd; + this.scanDecoder.SpectralEnd = this.temp[1]; int successiveApproximation = this.temp[2]; this.scanDecoder.SuccessiveHigh = successiveApproximation >> 4; diff --git a/src/ImageSharp/Formats/Jpeg/JpegImageFormatDetector.cs b/src/ImageSharp/Formats/Jpeg/JpegImageFormatDetector.cs index fbbe210ff0..61b4a36ad7 100644 --- a/src/ImageSharp/Formats/Jpeg/JpegImageFormatDetector.cs +++ b/src/ImageSharp/Formats/Jpeg/JpegImageFormatDetector.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -15,22 +15,18 @@ namespace SixLabors.ImageSharp.Formats.Jpeg /// public IImageFormat DetectFormat(ReadOnlySpan header) - { - return this.IsSupportedFileFormat(header) ? JpegFormat.Instance : null; - } + => this.IsSupportedFileFormat(header) ? JpegFormat.Instance : null; private bool IsSupportedFileFormat(ReadOnlySpan header) - { - return header.Length >= this.HeaderSize && - (this.IsJfif(header) || this.IsExif(header) || this.IsJpeg(header)); - } + => header.Length >= this.HeaderSize + && (IsJfif(header) || IsExif(header) || IsJpeg(header)); /// /// Returns a value indicating whether the given bytes identify Jfif data. /// /// The bytes representing the file header. /// The - private bool IsJfif(ReadOnlySpan header) => + private static bool IsJfif(ReadOnlySpan header) => header[6] == 0x4A && // J header[7] == 0x46 && // F header[8] == 0x49 && // I @@ -42,7 +38,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg /// /// The bytes representing the file header. /// The - private bool IsExif(ReadOnlySpan header) => + private static bool IsExif(ReadOnlySpan header) => header[6] == 0x45 && // E header[7] == 0x78 && // X header[8] == 0x69 && // I @@ -55,7 +51,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg /// /// The bytes representing the file header. /// The - private bool IsJpeg(ReadOnlySpan header) => + private static bool IsJpeg(ReadOnlySpan header) => header[0] == 0xFF && // 255 header[1] == 0xD8; // 216 } diff --git a/src/ImageSharp/Formats/Pbm/PbmImageFormatDetector.cs b/src/ImageSharp/Formats/Pbm/PbmImageFormatDetector.cs index b8d776a37d..4446d4b186 100644 --- a/src/ImageSharp/Formats/Pbm/PbmImageFormatDetector.cs +++ b/src/ImageSharp/Formats/Pbm/PbmImageFormatDetector.cs @@ -18,13 +18,11 @@ namespace SixLabors.ImageSharp.Formats.Pbm public int HeaderSize => 2; /// - public IImageFormat DetectFormat(ReadOnlySpan header) => this.IsSupportedFileFormat(header) ? PbmFormat.Instance : null; + public IImageFormat DetectFormat(ReadOnlySpan header) => IsSupportedFileFormat(header) ? PbmFormat.Instance : null; - private bool IsSupportedFileFormat(ReadOnlySpan header) + private static bool IsSupportedFileFormat(ReadOnlySpan header) { -#pragma warning disable SA1131 // Use readable conditions - if (1 < (uint)header.Length) -#pragma warning restore SA1131 // Use readable conditions + if ((uint)header.Length > 1) { // Signature should be between P1 and P6. return header[0] == P && (uint)(header[1] - Zero - 1) < (Seven - Zero - 1); diff --git a/src/ImageSharp/Formats/Png/PngDecoderCore.cs b/src/ImageSharp/Formats/Png/PngDecoderCore.cs index 9a1f89c47c..b7cd5dd932 100644 --- a/src/ImageSharp/Formats/Png/PngDecoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngDecoderCore.cs @@ -150,7 +150,7 @@ namespace SixLabors.ImageSharp.Formats.Png public Image Decode(BufferedReadStream stream, CancellationToken cancellationToken) where TPixel : unmanaged, IPixel { - var metadata = new ImageMetadata(); + ImageMetadata metadata = new(); PngMetadata pngMetadata = metadata.GetPngMetadata(); this.currentStream = stream; this.currentStream.Skip(8); @@ -250,7 +250,7 @@ namespace SixLabors.ImageSharp.Formats.Png /// public IImageInfo Identify(BufferedReadStream stream, CancellationToken cancellationToken) { - var metadata = new ImageMetadata(); + ImageMetadata metadata = new(); PngMetadata pngMetadata = metadata.GetPngMetadata(); this.currentStream = stream; this.currentStream.Skip(8); @@ -434,7 +434,7 @@ namespace SixLabors.ImageSharp.Formats.Png /// The data containing physical data. private static void ReadPhysicalChunk(ImageMetadata metadata, ReadOnlySpan data) { - var physicalChunk = PhysicalChunkData.Parse(data); + PhysicalChunkData physicalChunk = PhysicalChunkData.Parse(data); metadata.ResolutionUnits = physicalChunk.UnitSpecifier == byte.MinValue ? PixelResolutionUnit.AspectRatio @@ -560,7 +560,7 @@ namespace SixLabors.ImageSharp.Formats.Png private void ReadScanlines(PngChunk chunk, ImageFrame image, PngMetadata pngMetadata) where TPixel : unmanaged, IPixel { - using var deframeStream = new ZlibInflateStream(this.currentStream, this.ReadNextDataChunk); + using ZlibInflateStream deframeStream = new(this.currentStream, this.ReadNextDataChunk); deframeStream.AllocateNewBytes(chunk.Length, true); DeflateStream dataStream = deframeStream.CompressedStream; @@ -1018,7 +1018,7 @@ namespace SixLabors.ImageSharp.Formats.Png string value = PngConstants.Encoding.GetString(data[(zeroIndex + 1)..]); - if (!this.TryReadTextChunkMetadata(baseMetadata, name, value)) + if (!TryReadTextChunkMetadata(baseMetadata, name, value)) { metadata.TextData.Add(new PngTextData(name, value, string.Empty, string.Empty)); } @@ -1058,8 +1058,8 @@ namespace SixLabors.ImageSharp.Formats.Png ReadOnlySpan compressedData = data[(zeroIndex + 2)..]; - if (this.TryUncompressTextData(compressedData, PngConstants.Encoding, out string uncompressed) && - !this.TryReadTextChunkMetadata(baseMetadata, name, uncompressed)) + if (this.TryUncompressTextData(compressedData, PngConstants.Encoding, out string uncompressed) + && !TryReadTextChunkMetadata(baseMetadata, name, uncompressed)) { metadata.TextData.Add(new PngTextData(name, uncompressed, string.Empty, string.Empty)); } @@ -1074,10 +1074,10 @@ namespace SixLabors.ImageSharp.Formats.Png /// True if metadata was successfully parsed from the text chunk. False if the /// text chunk was not identified as metadata, and should be stored in the metadata /// object unmodified. - private bool TryReadTextChunkMetadata(ImageMetadata baseMetadata, string chunkName, string chunkText) + private static bool TryReadTextChunkMetadata(ImageMetadata baseMetadata, string chunkName, string chunkText) { if (chunkName.Equals("Raw profile type exif", StringComparison.OrdinalIgnoreCase) && - this.TryReadLegacyExifTextChunk(baseMetadata, chunkText)) + TryReadLegacyExifTextChunk(baseMetadata, chunkText)) { // Successfully parsed legacy exif data from text return true; @@ -1096,7 +1096,7 @@ namespace SixLabors.ImageSharp.Formats.Png /// /// The to store the decoded exif tags into. /// The contents of the "raw profile type exif" text chunk. - private bool TryReadLegacyExifTextChunk(ImageMetadata metadata, string data) + private static bool TryReadLegacyExifTextChunk(ImageMetadata metadata, string data) { ReadOnlySpan dataSpan = data.AsSpan(); dataSpan = dataSpan.TrimStart(); @@ -1219,10 +1219,10 @@ namespace SixLabors.ImageSharp.Formats.Png fixed (byte* compressedDataBase = compressedData) { using IMemoryOwner destBuffer = this.memoryAllocator.Allocate(this.configuration.StreamProcessingBufferSize); - using var memoryStreamOutput = new MemoryStream(compressedData.Length); - using var memoryStreamInput = new UnmanagedMemoryStream(compressedDataBase, compressedData.Length); - using var bufferedStream = new BufferedReadStream(this.configuration, memoryStreamInput); - using var inflateStream = new ZlibInflateStream(bufferedStream); + using MemoryStream memoryStreamOutput = new(compressedData.Length); + using UnmanagedMemoryStream memoryStreamInput = new(compressedDataBase, compressedData.Length); + using BufferedReadStream bufferedStream = new(this.configuration, memoryStreamInput); + using ZlibInflateStream inflateStream = new(bufferedStream); Span destUncompressedData = destBuffer.GetSpan(); if (!inflateStream.AllocateNewBytes(compressedData.Length, false)) @@ -1358,7 +1358,7 @@ namespace SixLabors.ImageSharp.Formats.Png } else if (IsXmpTextData(keywordBytes)) { - var xmpProfile = new XmpProfile(data[dataStartIdx..].ToArray()); + XmpProfile xmpProfile = new(data[dataStartIdx..].ToArray()); metadata.XmpProfile = xmpProfile; } else @@ -1561,18 +1561,17 @@ namespace SixLabors.ImageSharp.Formats.Png { return (PngChunkType)BinaryPrimitives.ReadUInt32BigEndian(this.buffer); } - else - { - PngThrowHelper.ThrowInvalidChunkType(); - // The IDE cannot detect the throw here. - return default; - } + PngThrowHelper.ThrowInvalidChunkType(); + + // The IDE cannot detect the throw here. + return default; } /// /// Attempts to read the length of the next chunk. /// + /// The result length. If the return type is this parameter is passed uninitialized. /// /// Whether the length was read. /// @@ -1613,10 +1612,13 @@ namespace SixLabors.ImageSharp.Formats.Png // Keywords should not be empty or have leading or trailing whitespace. name = PngConstants.Encoding.GetString(keywordBytes); - return !string.IsNullOrWhiteSpace(name) && !name.StartsWith(" ") && !name.EndsWith(" "); + return !string.IsNullOrWhiteSpace(name) + && !name.StartsWith(" ", StringComparison.Ordinal) + && !name.EndsWith(" ", StringComparison.Ordinal); } - private static bool IsXmpTextData(ReadOnlySpan keywordBytes) => keywordBytes.SequenceEqual(PngConstants.XmpKeyword); + private static bool IsXmpTextData(ReadOnlySpan keywordBytes) + => keywordBytes.SequenceEqual(PngConstants.XmpKeyword); private void SwapScanlineBuffers() => (this.scanline, this.previousScanline) = (this.previousScanline, this.scanline); diff --git a/src/ImageSharp/Formats/Png/PngEncoderCore.cs b/src/ImageSharp/Formats/Png/PngEncoderCore.cs index 11142ea648..7ba28393db 100644 --- a/src/ImageSharp/Formats/Png/PngEncoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngEncoderCore.cs @@ -245,62 +245,56 @@ namespace SixLabors.ImageSharp.Formats.Png } } } - else - { - if (this.bitDepth == 8) - { - // 8 bit grayscale - PixelOperations.Instance.ToL8Bytes( - this.configuration, - rowSpan, - rawScanlineSpan, - rowSpan.Length); - } - else - { - // 1, 2, and 4 bit grayscale - using IMemoryOwner temp = this.memoryAllocator.Allocate(rowSpan.Length, AllocationOptions.Clean); - int scaleFactor = 255 / (ColorNumerics.GetColorCountForBitDepth(this.bitDepth) - 1); - Span tempSpan = temp.GetSpan(); - - // We need to first create an array of luminance bytes then scale them down to the correct bit depth. - PixelOperations.Instance.ToL8Bytes( - this.configuration, - rowSpan, - tempSpan, - rowSpan.Length); - PngEncoderHelpers.ScaleDownFrom8BitArray(tempSpan, rawScanlineSpan, this.bitDepth, scaleFactor); - } - } - } - else - { - if (this.use16Bit) + else if (this.bitDepth == 8) { - // 16 bit grayscale + alpha - using IMemoryOwner laBuffer = this.memoryAllocator.Allocate(rowSpan.Length); - Span laSpan = laBuffer.GetSpan(); - ref La32 laRef = ref MemoryMarshal.GetReference(laSpan); - PixelOperations.Instance.ToLa32(this.configuration, rowSpan, laSpan); - - // Can't map directly to byte array as it's big endian. - for (int x = 0, o = 0; x < laSpan.Length; x++, o += 4) - { - La32 la = Unsafe.Add(ref laRef, x); - BinaryPrimitives.WriteUInt16BigEndian(rawScanlineSpan.Slice(o, 2), la.L); - BinaryPrimitives.WriteUInt16BigEndian(rawScanlineSpan.Slice(o + 2, 2), la.A); - } + // 8 bit grayscale + PixelOperations.Instance.ToL8Bytes( + this.configuration, + rowSpan, + rawScanlineSpan, + rowSpan.Length); } else { - // 8 bit grayscale + alpha - PixelOperations.Instance.ToLa16Bytes( + // 1, 2, and 4 bit grayscale + using IMemoryOwner temp = this.memoryAllocator.Allocate(rowSpan.Length, AllocationOptions.Clean); + int scaleFactor = 255 / (ColorNumerics.GetColorCountForBitDepth(this.bitDepth) - 1); + Span tempSpan = temp.GetSpan(); + + // We need to first create an array of luminance bytes then scale them down to the correct bit depth. + PixelOperations.Instance.ToL8Bytes( this.configuration, rowSpan, - rawScanlineSpan, + tempSpan, rowSpan.Length); + PngEncoderHelpers.ScaleDownFrom8BitArray(tempSpan, rawScanlineSpan, this.bitDepth, scaleFactor); } } + else if (this.use16Bit) + { + // 16 bit grayscale + alpha + using IMemoryOwner laBuffer = this.memoryAllocator.Allocate(rowSpan.Length); + Span laSpan = laBuffer.GetSpan(); + ref La32 laRef = ref MemoryMarshal.GetReference(laSpan); + PixelOperations.Instance.ToLa32(this.configuration, rowSpan, laSpan); + + // Can't map directly to byte array as it's big endian. + for (int x = 0, o = 0; x < laSpan.Length; x++, o += 4) + { + La32 la = Unsafe.Add(ref laRef, x); + BinaryPrimitives.WriteUInt16BigEndian(rawScanlineSpan.Slice(o, 2), la.L); + BinaryPrimitives.WriteUInt16BigEndian(rawScanlineSpan.Slice(o + 2, 2), la.A); + } + } + else + { + // 8 bit grayscale + alpha + PixelOperations.Instance.ToLa16Bytes( + this.configuration, + rowSpan, + rawScanlineSpan, + rowSpan.Length); + } } /// @@ -316,7 +310,7 @@ namespace SixLabors.ImageSharp.Formats.Png switch (this.bytesPerPixel) { case 4: - { + // 8 bit Rgba PixelOperations.Instance.ToRgba32Bytes( this.configuration, @@ -324,10 +318,9 @@ namespace SixLabors.ImageSharp.Formats.Png rawScanlineSpan, rowSpan.Length); break; - } case 3: - { + // 8 bit Rgb PixelOperations.Instance.ToRgb24Bytes( this.configuration, @@ -335,10 +328,9 @@ namespace SixLabors.ImageSharp.Formats.Png rawScanlineSpan, rowSpan.Length); break; - } case 8: - { + // 16 bit Rgba using (IMemoryOwner rgbaBuffer = this.memoryAllocator.Allocate(rowSpan.Length)) { @@ -358,10 +350,9 @@ namespace SixLabors.ImageSharp.Formats.Png } break; - } default: - { + // 16 bit Rgb using (IMemoryOwner rgbBuffer = this.memoryAllocator.Allocate(rowSpan.Length)) { @@ -380,7 +371,6 @@ namespace SixLabors.ImageSharp.Formats.Png } break; - } } } @@ -413,8 +403,6 @@ namespace SixLabors.ImageSharp.Formats.Png case PngColorType.GrayscaleWithAlpha: this.CollectGrayscaleBytes(rowSpan); break; - case PngColorType.Rgb: - case PngColorType.RgbWithAlpha: default: this.CollectTPixelBytes(rowSpan); break; @@ -424,6 +412,8 @@ namespace SixLabors.ImageSharp.Formats.Png /// /// Apply the line filter for the raw scanline to enable better compression. /// + /// The filtered buffer. + /// Used for attempting optimized filtering. private void FilterPixelBytes(ref Span filter, ref Span attempt) { switch (this.options.FilterMethod) @@ -446,7 +436,6 @@ namespace SixLabors.ImageSharp.Formats.Png case PngFilterMethod.Paeth: PaethFilter.Encode(this.currentScanline.GetSpan(), this.previousScanline.GetSpan(), filter, this.bytesPerPixel, out int _); break; - case PngFilterMethod.Adaptive: default: this.ApplyOptimalFilteredScanline(ref filter, ref attempt); break; @@ -503,6 +492,8 @@ namespace SixLabors.ImageSharp.Formats.Png /// Applies all PNG filters to the given scanline and returns the filtered scanline that is deemed /// to be most compressible, using lowest total variation as proxy for compressibility. /// + /// The filtered buffer. + /// Used for attempting optimized filtering. private void ApplyOptimalFilteredScanline(ref Span filter, ref Span attempt) { // Palette images don't compress well with adaptive filtering. @@ -551,7 +542,7 @@ namespace SixLabors.ImageSharp.Formats.Png /// The containing image data. private void WriteHeaderChunk(Stream stream) { - var header = new PngHeader( + PngHeader header = new( width: this.width, height: this.height, bitDepth: this.bitDepth, @@ -688,25 +679,24 @@ namespace SixLabors.ImageSharp.Formats.Png } int payloadLength = xmpData.Length + PngConstants.XmpKeyword.Length + iTxtHeaderSize; - using (IMemoryOwner owner = this.memoryAllocator.Allocate(payloadLength)) - { - Span payload = owner.GetSpan(); - PngConstants.XmpKeyword.CopyTo(payload); - int bytesWritten = PngConstants.XmpKeyword.Length; - - // Write the iTxt header (all zeros in this case). - Span iTxtHeader = payload[bytesWritten..]; - iTxtHeader[4] = 0; - iTxtHeader[3] = 0; - iTxtHeader[2] = 0; - iTxtHeader[1] = 0; - iTxtHeader[0] = 0; - bytesWritten += 5; - - // And the XMP data itself. - xmpData.CopyTo(payload[bytesWritten..]); - this.WriteChunk(stream, PngChunkType.InternationalText, payload); - } + + using IMemoryOwner owner = this.memoryAllocator.Allocate(payloadLength); + Span payload = owner.GetSpan(); + PngConstants.XmpKeyword.CopyTo(payload); + int bytesWritten = PngConstants.XmpKeyword.Length; + + // Write the iTxt header (all zeros in this case). + Span iTxtHeader = payload[bytesWritten..]; + iTxtHeader[4] = 0; + iTxtHeader[3] = 0; + iTxtHeader[2] = 0; + iTxtHeader[1] = 0; + iTxtHeader[0] = 0; + bytesWritten += 5; + + // And the XMP data itself. + xmpData.CopyTo(payload[bytesWritten..]); + this.WriteChunk(stream, PngChunkType.InternationalText, payload); } /// @@ -725,16 +715,15 @@ namespace SixLabors.ImageSharp.Formats.Png byte[] compressedData = this.GetZlibCompressedBytes(iccProfileBytes); int payloadLength = ColorProfileName.Length + compressedData.Length + 2; - using (IMemoryOwner owner = this.memoryAllocator.Allocate(payloadLength)) - { - Span outputBytes = owner.GetSpan(); - PngConstants.Encoding.GetBytes(ColorProfileName).CopyTo(outputBytes); - int bytesWritten = ColorProfileName.Length; - outputBytes[bytesWritten++] = 0; // Null separator. - outputBytes[bytesWritten++] = 0; // Compression. - compressedData.CopyTo(outputBytes[bytesWritten..]); - this.WriteChunk(stream, PngChunkType.EmbeddedColorProfile, outputBytes); - } + + using IMemoryOwner owner = this.memoryAllocator.Allocate(payloadLength); + Span outputBytes = owner.GetSpan(); + PngConstants.Encoding.GetBytes(ColorProfileName).CopyTo(outputBytes); + int bytesWritten = ColorProfileName.Length; + outputBytes[bytesWritten++] = 0; // Null separator. + outputBytes[bytesWritten++] = 0; // Compression. + compressedData.CopyTo(outputBytes[bytesWritten..]); + this.WriteChunk(stream, PngChunkType.EmbeddedColorProfile, outputBytes); } /// @@ -776,65 +765,59 @@ namespace SixLabors.ImageSharp.Formats.Png byte[] languageTag = PngConstants.LanguageEncoding.GetBytes(textData.LanguageTag); int payloadLength = keywordBytes.Length + textBytes.Length + translatedKeyword.Length + languageTag.Length + 5; - using (IMemoryOwner owner = this.memoryAllocator.Allocate(payloadLength)) - { - Span outputBytes = owner.GetSpan(); - keywordBytes.CopyTo(outputBytes); - int bytesWritten = keywordBytes.Length; - outputBytes[bytesWritten++] = 0; - if (textData.Value.Length > this.options.TextCompressionThreshold) - { - // Indicate that the text is compressed. - outputBytes[bytesWritten++] = 1; - } - else - { - outputBytes[bytesWritten++] = 0; - } - outputBytes[bytesWritten++] = 0; - languageTag.CopyTo(outputBytes[bytesWritten..]); - bytesWritten += languageTag.Length; - outputBytes[bytesWritten++] = 0; - translatedKeyword.CopyTo(outputBytes[bytesWritten..]); - bytesWritten += translatedKeyword.Length; - outputBytes[bytesWritten++] = 0; - textBytes.CopyTo(outputBytes[bytesWritten..]); - this.WriteChunk(stream, PngChunkType.InternationalText, outputBytes); - } - } - else - { + using IMemoryOwner owner = this.memoryAllocator.Allocate(payloadLength); + Span outputBytes = owner.GetSpan(); + keywordBytes.CopyTo(outputBytes); + int bytesWritten = keywordBytes.Length; + outputBytes[bytesWritten++] = 0; if (textData.Value.Length > this.options.TextCompressionThreshold) { - // Write zTXt chunk. - byte[] compressedData = this.GetZlibCompressedBytes(PngConstants.Encoding.GetBytes(textData.Value)); - int payloadLength = textData.Keyword.Length + compressedData.Length + 2; - using (IMemoryOwner owner = this.memoryAllocator.Allocate(payloadLength)) - { - Span outputBytes = owner.GetSpan(); - PngConstants.Encoding.GetBytes(textData.Keyword).CopyTo(outputBytes); - int bytesWritten = textData.Keyword.Length; - outputBytes[bytesWritten++] = 0; // Null separator. - outputBytes[bytesWritten++] = 0; // Compression. - compressedData.CopyTo(outputBytes[bytesWritten..]); - this.WriteChunk(stream, PngChunkType.CompressedText, outputBytes); - } + // Indicate that the text is compressed. + outputBytes[bytesWritten++] = 1; } else { - // Write tEXt chunk. - int payloadLength = textData.Keyword.Length + textData.Value.Length + 1; - using (IMemoryOwner owner = this.memoryAllocator.Allocate(payloadLength)) - { - Span outputBytes = owner.GetSpan(); - PngConstants.Encoding.GetBytes(textData.Keyword).CopyTo(outputBytes); - int bytesWritten = textData.Keyword.Length; - outputBytes[bytesWritten++] = 0; - PngConstants.Encoding.GetBytes(textData.Value).CopyTo(outputBytes[bytesWritten..]); - this.WriteChunk(stream, PngChunkType.Text, outputBytes); - } + outputBytes[bytesWritten++] = 0; } + + outputBytes[bytesWritten++] = 0; + languageTag.CopyTo(outputBytes[bytesWritten..]); + bytesWritten += languageTag.Length; + outputBytes[bytesWritten++] = 0; + translatedKeyword.CopyTo(outputBytes[bytesWritten..]); + bytesWritten += translatedKeyword.Length; + outputBytes[bytesWritten++] = 0; + textBytes.CopyTo(outputBytes[bytesWritten..]); + this.WriteChunk(stream, PngChunkType.InternationalText, outputBytes); + } + else if (textData.Value.Length > this.options.TextCompressionThreshold) + { + // Write zTXt chunk. + byte[] compressedData = this.GetZlibCompressedBytes(PngConstants.Encoding.GetBytes(textData.Value)); + int payloadLength = textData.Keyword.Length + compressedData.Length + 2; + + using IMemoryOwner owner = this.memoryAllocator.Allocate(payloadLength); + Span outputBytes = owner.GetSpan(); + PngConstants.Encoding.GetBytes(textData.Keyword).CopyTo(outputBytes); + int bytesWritten = textData.Keyword.Length; + outputBytes[bytesWritten++] = 0; // Null separator. + outputBytes[bytesWritten++] = 0; // Compression. + compressedData.CopyTo(outputBytes[bytesWritten..]); + this.WriteChunk(stream, PngChunkType.CompressedText, outputBytes); + } + else + { + // Write tEXt chunk. + int payloadLength = textData.Keyword.Length + textData.Value.Length + 1; + + using IMemoryOwner owner = this.memoryAllocator.Allocate(payloadLength); + Span outputBytes = owner.GetSpan(); + PngConstants.Encoding.GetBytes(textData.Keyword).CopyTo(outputBytes); + int bytesWritten = textData.Keyword.Length; + outputBytes[bytesWritten++] = 0; + PngConstants.Encoding.GetBytes(textData.Value).CopyTo(outputBytes[bytesWritten..]); + this.WriteChunk(stream, PngChunkType.Text, outputBytes); } } } @@ -846,15 +829,13 @@ namespace SixLabors.ImageSharp.Formats.Png /// The compressed byte array. private byte[] GetZlibCompressedBytes(byte[] dataBytes) { - using (var memoryStream = new MemoryStream()) + using MemoryStream memoryStream = new(); + using (ZlibDeflateStream deflateStream = new(this.memoryAllocator, memoryStream, this.options.CompressionLevel)) { - using (var deflateStream = new ZlibDeflateStream(this.memoryAllocator, memoryStream, this.options.CompressionLevel)) - { - deflateStream.Write(dataBytes); - } - - return memoryStream.ToArray(); + deflateStream.Write(dataBytes); } + + return memoryStream.ToArray(); } /// @@ -944,9 +925,9 @@ namespace SixLabors.ImageSharp.Formats.Png byte[] buffer; int bufferLength; - using (var memoryStream = new MemoryStream()) + using (MemoryStream memoryStream = new()) { - using (var deflateStream = new ZlibDeflateStream(this.memoryAllocator, memoryStream, this.options.CompressionLevel)) + using (ZlibDeflateStream deflateStream = new(this.memoryAllocator, memoryStream, this.options.CompressionLevel)) { if (this.options.InterlaceMethod == PngInterlaceMode.Adam7) { @@ -1174,7 +1155,7 @@ namespace SixLabors.ImageSharp.Formats.Png uint crc = Crc32.Calculate(this.buffer.AsSpan(4, 4)); // Write the type buffer - if (data != null && length > 0) + if (data.Length > 0 && length > 0) { stream.Write(data, offset, length); diff --git a/src/ImageSharp/Formats/Png/PngTextData.cs b/src/ImageSharp/Formats/Png/PngTextData.cs index 3d495cba6e..7db26b60be 100644 --- a/src/ImageSharp/Formats/Png/PngTextData.cs +++ b/src/ImageSharp/Formats/Png/PngTextData.cs @@ -72,9 +72,7 @@ namespace SixLabors.ImageSharp.Formats.Png /// True if the current left is equal to the parameter; otherwise, false. /// public static bool operator ==(PngTextData left, PngTextData right) - { - return left.Equals(right); - } + => left.Equals(right); /// /// Compares two objects. The result specifies whether the values @@ -90,9 +88,7 @@ namespace SixLabors.ImageSharp.Formats.Png /// True if the current left is unequal to the parameter; otherwise, false. /// public static bool operator !=(PngTextData left, PngTextData right) - { - return !(left == right); - } + => !(left == right); /// /// Indicates whether this instance and a specified object are equal. @@ -105,9 +101,7 @@ namespace SixLabors.ImageSharp.Formats.Png /// same value; otherwise, false. /// public override bool Equals(object obj) - { - return obj is PngTextData other && this.Equals(other); - } + => obj is PngTextData other && this.Equals(other); /// /// Returns the hash code for this instance. @@ -115,7 +109,8 @@ namespace SixLabors.ImageSharp.Formats.Png /// /// A 32-bit signed integer that is the hash code for this instance. /// - public override int GetHashCode() => HashCode.Combine(this.Keyword, this.Value, this.LanguageTag, this.TranslatedKeyword); + public override int GetHashCode() + => HashCode.Combine(this.Keyword, this.Value, this.LanguageTag, this.TranslatedKeyword); /// /// Returns the fully qualified type name of this instance. @@ -123,7 +118,8 @@ namespace SixLabors.ImageSharp.Formats.Png /// /// A containing a fully qualified type name. /// - public override string ToString() => $"PngTextData [ Name={this.Keyword}, Value={this.Value} ]"; + public override string ToString() + => $"PngTextData [ Name={this.Keyword}, Value={this.Value} ]"; /// /// Indicates whether the current object is equal to another object of the same type. @@ -133,11 +129,9 @@ namespace SixLabors.ImageSharp.Formats.Png /// /// An object to compare with this object. public bool Equals(PngTextData other) - { - return this.Keyword.Equals(other.Keyword) - && this.Value.Equals(other.Value) - && this.LanguageTag.Equals(other.LanguageTag) - && this.TranslatedKeyword.Equals(other.TranslatedKeyword); - } + => this.Keyword.Equals(other.Keyword, StringComparison.OrdinalIgnoreCase) + && this.Value.Equals(other.Value, StringComparison.OrdinalIgnoreCase) + && this.LanguageTag.Equals(other.LanguageTag, StringComparison.OrdinalIgnoreCase) + && this.TranslatedKeyword.Equals(other.TranslatedKeyword, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/ImageSharp/Formats/Png/PngThrowHelper.cs b/src/ImageSharp/Formats/Png/PngThrowHelper.cs index 7cf954f1d6..c62775f87a 100644 --- a/src/ImageSharp/Formats/Png/PngThrowHelper.cs +++ b/src/ImageSharp/Formats/Png/PngThrowHelper.cs @@ -2,6 +2,7 @@ // Licensed under the Six Labors Split License. using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace SixLabors.ImageSharp.Formats.Png @@ -11,31 +12,40 @@ namespace SixLabors.ImageSharp.Formats.Png /// internal static class PngThrowHelper { + [DoesNotReturn] [MethodImpl(InliningOptions.ColdPath)] public static void ThrowInvalidImageContentException(string errorMessage, Exception innerException) => throw new InvalidImageContentException(errorMessage, innerException); + [DoesNotReturn] [MethodImpl(InliningOptions.ColdPath)] public static void ThrowNoHeader() => throw new InvalidImageContentException("PNG Image does not contain a header chunk"); + [DoesNotReturn] [MethodImpl(InliningOptions.ColdPath)] public static void ThrowNoData() => throw new InvalidImageContentException("PNG Image does not contain a data chunk"); + [DoesNotReturn] [MethodImpl(InliningOptions.ColdPath)] public static void ThrowMissingPalette() => throw new InvalidImageContentException("PNG Image does not contain a palette chunk"); + [DoesNotReturn] [MethodImpl(InliningOptions.ColdPath)] public static void ThrowInvalidChunkType() => throw new InvalidImageContentException("Invalid PNG data."); + [DoesNotReturn] [MethodImpl(InliningOptions.ColdPath)] public static void ThrowInvalidChunkType(string message) => throw new InvalidImageContentException(message); + [DoesNotReturn] [MethodImpl(InliningOptions.ColdPath)] public static void ThrowInvalidChunkCrc(string chunkTypeName) => throw new InvalidImageContentException($"CRC Error. PNG {chunkTypeName} chunk is corrupt!"); + [DoesNotReturn] [MethodImpl(InliningOptions.ColdPath)] public static void ThrowNotSupportedColor() => throw new NotSupportedException("Unsupported PNG color type"); + [DoesNotReturn] [MethodImpl(InliningOptions.ColdPath)] public static void ThrowUnknownFilter() => throw new InvalidImageContentException("Unknown filter type."); } diff --git a/src/ImageSharp/Formats/Tga/TgaEncoderCore.cs b/src/ImageSharp/Formats/Tga/TgaEncoderCore.cs index fa0ea6f90b..5cfdf3022c 100644 --- a/src/ImageSharp/Formats/Tga/TgaEncoderCore.cs +++ b/src/ImageSharp/Formats/Tga/TgaEncoderCore.cs @@ -5,6 +5,7 @@ using System; using System.Buffers; using System.Buffers.Binary; using System.IO; +using System.Numerics; using System.Runtime.CompilerServices; using System.Threading; using SixLabors.ImageSharp.Advanced; @@ -99,7 +100,7 @@ namespace SixLabors.ImageSharp.Formats.Tga imageDescriptor |= 0x1; } - var fileHeader = new TgaFileHeader( + TgaFileHeader fileHeader = new( idLength: 0, colorMapType: 0, imageType: imageType, @@ -158,8 +159,6 @@ namespace SixLabors.ImageSharp.Formats.Tga case TgaBitsPerPixel.Pixel32: this.Write32Bit(stream, pixels); break; - default: - break; } } @@ -181,7 +180,7 @@ namespace SixLabors.ImageSharp.Formats.Tga { TPixel currentPixel = pixelRow[x]; currentPixel.ToRgba32(ref color); - byte equalPixelCount = this.FindEqualPixels(pixelRow, x); + byte equalPixelCount = FindEqualPixels(pixelRow, x); if (equalPixelCount > 0) { @@ -193,7 +192,7 @@ namespace SixLabors.ImageSharp.Formats.Tga else { // Write Raw Packet (i.e., Non-Run-Length Encoded): - byte unEqualPixelCount = this.FindUnEqualPixels(pixelRow, x); + byte unEqualPixelCount = FindUnEqualPixels(pixelRow, x); stream.WriteByte(unEqualPixelCount); this.WritePixel(stream, currentPixel, color); x++; @@ -227,7 +226,7 @@ namespace SixLabors.ImageSharp.Formats.Tga break; case TgaBitsPerPixel.Pixel16: - var bgra5551 = new Bgra5551(color.ToVector4()); + Bgra5551 bgra5551 = new(color.ToVector4()); BinaryPrimitives.TryWriteInt16LittleEndian(this.buffer, (short)bgra5551.PackedValue); stream.WriteByte(this.buffer[0]); stream.WriteByte(this.buffer[1]); @@ -246,8 +245,6 @@ namespace SixLabors.ImageSharp.Formats.Tga stream.WriteByte(color.R); stream.WriteByte(color.A); break; - default: - break; } } @@ -258,7 +255,7 @@ namespace SixLabors.ImageSharp.Formats.Tga /// A pixel row of the image to encode. /// X coordinate to start searching for the same pixels. /// The number of equal pixels. - private byte FindEqualPixels(Span pixelRow, int xStart) + private static byte FindEqualPixels(Span pixelRow, int xStart) where TPixel : unmanaged, IPixel { byte equalPixelCount = 0; @@ -291,7 +288,7 @@ namespace SixLabors.ImageSharp.Formats.Tga /// A pixel row of the image to encode. /// X coordinate to start searching for the unequal pixels. /// The number of equal pixels. - private byte FindUnEqualPixels(Span pixelRow, int xStart) + private static byte FindUnEqualPixels(Span pixelRow, int xStart) where TPixel : unmanaged, IPixel { byte unEqualPixelCount = 0; @@ -419,12 +416,13 @@ namespace SixLabors.ImageSharp.Formats.Tga /// /// Convert the pixel values to grayscale using ITU-R Recommendation BT.709. /// + /// The type of pixel format. /// The pixel to get the luminance from. [MethodImpl(InliningOptions.ShortMethod)] public static int GetLuminance(TPixel sourcePixel) where TPixel : unmanaged, IPixel { - var vector = sourcePixel.ToVector4(); + Vector4 vector = sourcePixel.ToVector4(); return ColorNumerics.GetBT709Luminance(ref vector, 256); } } diff --git a/src/ImageSharp/Formats/Tga/TgaMetadata.cs b/src/ImageSharp/Formats/Tga/TgaMetadata.cs index a29eac21e4..61b92d7313 100644 --- a/src/ImageSharp/Formats/Tga/TgaMetadata.cs +++ b/src/ImageSharp/Formats/Tga/TgaMetadata.cs @@ -20,9 +20,7 @@ namespace SixLabors.ImageSharp.Formats.Tga /// /// The metadata to create an instance from. private TgaMetadata(TgaMetadata other) - { - this.BitsPerPixel = other.BitsPerPixel; - } + => this.BitsPerPixel = other.BitsPerPixel; /// /// Gets or sets the number of bits per pixel. @@ -30,9 +28,9 @@ namespace SixLabors.ImageSharp.Formats.Tga public TgaBitsPerPixel BitsPerPixel { get; set; } = TgaBitsPerPixel.Pixel24; /// - /// Gets or sets the the number of alpha bits per pixel. + /// Gets or sets the number of alpha bits per pixel. /// - public byte AlphaChannelBits { get; set; } = 0; + public byte AlphaChannelBits { get; set; } /// public IDeepCloneable DeepClone() => new TgaMetadata(this); diff --git a/src/ImageSharp/Formats/Tiff/Compression/Compressors/T4BitCompressor.cs b/src/ImageSharp/Formats/Tiff/Compression/Compressors/T4BitCompressor.cs index 11bc49f27e..7c3ecc643e 100644 --- a/src/ImageSharp/Formats/Tiff/Compression/Compressors/T4BitCompressor.cs +++ b/src/ImageSharp/Formats/Tiff/Compression/Compressors/T4BitCompressor.cs @@ -93,14 +93,14 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors uint codeLength; if (runLength <= 63) { - code = this.GetTermCode(runLength, out codeLength, isWhiteRun); + code = GetTermCode(runLength, out codeLength, isWhiteRun); this.WriteCode(codeLength, code, compressedData); x += (int)runLength; } else { - runLength = this.GetBestFittingMakeupRunLength(runLength); - code = this.GetMakeupCode(runLength, out codeLength, isWhiteRun); + runLength = GetBestFittingMakeupRunLength(runLength); + code = GetMakeupCode(runLength, out codeLength, isWhiteRun); this.WriteCode(codeLength, code, compressedData); x += (int)runLength; diff --git a/src/ImageSharp/Formats/Tiff/Compression/Compressors/T6BitCompressor.cs b/src/ImageSharp/Formats/Tiff/Compression/Compressors/T6BitCompressor.cs index 7e0b6042cb..99b4a9fccc 100644 --- a/src/ImageSharp/Formats/Tiff/Compression/Compressors/T6BitCompressor.cs +++ b/src/ImageSharp/Formats/Tiff/Compression/Compressors/T6BitCompressor.cs @@ -61,12 +61,12 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors { Span row = pixelsAsGray.Slice(y * this.Width, this.Width); uint a0 = 0; - uint a1 = row[0] == 0 ? 0 : this.FindRunEnd(row, 0); - uint b1 = referenceLine[0] == 0 ? 0 : this.FindRunEnd(referenceLine, 0); + uint a1 = row[0] == 0 ? 0 : FindRunEnd(row, 0); + uint b1 = referenceLine[0] == 0 ? 0 : FindRunEnd(referenceLine, 0); while (true) { - uint b2 = this.FindRunEnd(referenceLine, b1); + uint b2 = FindRunEnd(referenceLine, b1); if (b2 < a1) { // Pass mode. @@ -85,7 +85,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors d = -(int)(a1 - b1); } - if ((d >= -3) && (d <= 3)) + if (d is >= -3 and <= 3) { // Vertical mode. (uint length, uint code) = VerticalCodes[d + 3]; @@ -97,7 +97,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors // Horizontal mode. this.WriteCode(3, 1, compressedData); - uint a2 = this.FindRunEnd(row, a1); + uint a2 = FindRunEnd(row, a1); if ((a0 + a1 == 0) || (row[(int)a0] != 0)) { this.WriteRun(a1 - a0, true, compressedData); @@ -119,9 +119,9 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors } byte thisPixel = row[(int)a0]; - a1 = this.FindRunEnd(row, a0, thisPixel); - b1 = this.FindRunEnd(referenceLine, a0, (byte)~thisPixel); - b1 = this.FindRunEnd(referenceLine, b1, thisPixel); + a1 = FindRunEnd(row, a0, thisPixel); + b1 = FindRunEnd(referenceLine, a0, (byte)~thisPixel); + b1 = FindRunEnd(referenceLine, b1, thisPixel); } // This row is now the reference line. @@ -149,14 +149,14 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors /// The index of the first pixel at or after /// that does not match , or the length of , /// whichever comes first. - private uint FindRunEnd(Span row, uint startIndex, byte? color = null) + private static uint FindRunEnd(Span row, uint startIndex, byte? color = null) { if (startIndex >= row.Length) { return (uint)row.Length; } - byte colorValue = color.GetValueOrDefault(row[(int)startIndex]); + byte colorValue = color ?? row[(int)startIndex]; for (int i = (int)startIndex; i < row.Length; i++) { if (row[i] != colorValue) @@ -188,13 +188,13 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors uint codeLength; while (runLength > 63) { - uint makeupLength = this.GetBestFittingMakeupRunLength(runLength); - code = this.GetMakeupCode(makeupLength, out codeLength, isWhiteRun); + uint makeupLength = GetBestFittingMakeupRunLength(runLength); + code = GetMakeupCode(makeupLength, out codeLength, isWhiteRun); this.WriteCode(codeLength, code, compressedData); runLength -= makeupLength; } - code = this.GetTermCode(runLength, out codeLength, isWhiteRun); + code = GetTermCode(runLength, out codeLength, isWhiteRun); this.WriteCode(codeLength, code, compressedData); } } diff --git a/src/ImageSharp/Formats/Tiff/Compression/Compressors/TiffCcittCompressor.cs b/src/ImageSharp/Formats/Tiff/Compression/Compressors/TiffCcittCompressor.cs index b1f5c85d9e..8ff41ed07e 100644 --- a/src/ImageSharp/Formats/Tiff/Compression/Compressors/TiffCcittCompressor.cs +++ b/src/ImageSharp/Formats/Tiff/Compression/Compressors/TiffCcittCompressor.cs @@ -195,7 +195,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors this.bitPosition = 0; } - private uint GetWhiteMakeupCode(uint runLength, out uint codeLength) + private static uint GetWhiteMakeupCode(uint runLength, out uint codeLength) { codeLength = 0; @@ -244,7 +244,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors return 0; } - private uint GetBlackMakeupCode(uint runLength, out uint codeLength) + private static uint GetBlackMakeupCode(uint runLength, out uint codeLength) { codeLength = 0; @@ -275,7 +275,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors return 0; } - private uint GetWhiteTermCode(uint runLength, out uint codeLength) + private static uint GetWhiteTermCode(uint runLength, out uint codeLength) { codeLength = 0; @@ -312,7 +312,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors return 0; } - private uint GetBlackTermCode(uint runLength, out uint codeLength) + private static uint GetBlackTermCode(uint runLength, out uint codeLength) { codeLength = 0; @@ -390,7 +390,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors /// /// A run length needing a makeup code /// The makeup length for . - protected uint GetBestFittingMakeupRunLength(uint runLength) + protected static uint GetBestFittingMakeupRunLength(uint runLength) { DebugGuard.MustBeGreaterThanOrEqualTo(runLength, MakeupRunLength[0], nameof(runLength)); @@ -402,7 +402,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors } } - return MakeupRunLength[MakeupRunLength.Length - 1]; + return MakeupRunLength[^1]; } /// @@ -413,14 +413,14 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors /// If true, the run is of white pixels. /// If false the run is of black pixels /// The terminating code for a run of length - protected uint GetTermCode(uint runLength, out uint codeLength, bool isWhiteRun) + protected static uint GetTermCode(uint runLength, out uint codeLength, bool isWhiteRun) { if (isWhiteRun) { - return this.GetWhiteTermCode(runLength, out codeLength); + return GetWhiteTermCode(runLength, out codeLength); } - return this.GetBlackTermCode(runLength, out codeLength); + return GetBlackTermCode(runLength, out codeLength); } /// @@ -431,14 +431,14 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors /// If true, the run is of white pixels. /// If false the run is of black pixels /// The makeup code for a run of length - protected uint GetMakeupCode(uint runLength, out uint codeLength, bool isWhiteRun) + protected static uint GetMakeupCode(uint runLength, out uint codeLength, bool isWhiteRun) { if (isWhiteRun) { - return this.GetWhiteMakeupCode(runLength, out codeLength); + return GetWhiteMakeupCode(runLength, out codeLength); } - return this.GetBlackMakeupCode(runLength, out codeLength); + return GetBlackMakeupCode(runLength, out codeLength); } /// @@ -494,12 +494,12 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors /// /// Writes a image compressed with CCITT T6 to the stream. /// - /// The pixels as 8-bit gray array. + /// The pixels as 8-bit gray array. /// The strip height. - public override void CompressStrip(Span pixelsAsGray, int height) + public override void CompressStrip(Span rows, int height) { - DebugGuard.IsTrue(pixelsAsGray.Length / height == this.Width, "Values must be equals"); - DebugGuard.IsTrue(pixelsAsGray.Length % height == 0, "Values must be equals"); + DebugGuard.IsTrue(rows.Length / height == this.Width, "Values must be equals"); + DebugGuard.IsTrue(rows.Length % height == 0, "Values must be equals"); this.compressedDataBuffer.Clear(); Span compressedData = this.compressedDataBuffer.GetSpan(); @@ -507,7 +507,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Compression.Compressors this.bytePosition = 0; this.bitPosition = 0; - this.CompressStrip(pixelsAsGray, height, compressedData); + this.CompressStrip(rows, height, compressedData); // Write the compressed data to the stream. int bytesToWrite = this.bitPosition != 0 ? this.bytePosition + 1 : this.bytePosition; diff --git a/src/ImageSharp/Formats/Tiff/TiffBitsPerSample.cs b/src/ImageSharp/Formats/Tiff/TiffBitsPerSample.cs index 2412d166b4..d277af9003 100644 --- a/src/ImageSharp/Formats/Tiff/TiffBitsPerSample.cs +++ b/src/ImageSharp/Formats/Tiff/TiffBitsPerSample.cs @@ -10,31 +10,6 @@ namespace SixLabors.ImageSharp.Formats.Tiff /// public readonly struct TiffBitsPerSample : IEquatable { - /// - /// The bits for the channel 0. - /// - public readonly ushort Channel0; - - /// - /// The bits for the channel 1. - /// - public readonly ushort Channel1; - - /// - /// The bits for the channel 2. - /// - public readonly ushort Channel2; - - /// - /// The bits for the alpha channel. - /// - public readonly ushort Channel3; - - /// - /// The number of channels. - /// - public readonly byte Channels; - /// /// Initializes a new instance of the struct. /// @@ -56,6 +31,53 @@ namespace SixLabors.ImageSharp.Formats.Tiff this.Channels += (byte)(this.Channel3 != 0 ? 1 : 0); } + /// + /// Gets the bits for the channel 0. + /// + public readonly ushort Channel0 { get; } + + /// + /// Gets the bits for the channel 1. + /// + public readonly ushort Channel1 { get; } + + /// + /// Gets the bits for the channel 2. + /// + public readonly ushort Channel2 { get; } + + /// + /// Gets the bits for the alpha channel. + /// + public readonly ushort Channel3 { get; } + + /// + /// Gets the number of channels. + /// + public readonly byte Channels { get; } + + /// + /// Checks whether two structures are equal. + /// + /// The left hand operand. + /// The right hand operand. + /// + /// True if the parameter is equal to the parameter; + /// otherwise, false. + /// + public static bool operator ==(TiffBitsPerSample left, TiffBitsPerSample right) => left.Equals(right); + + /// + /// Checks whether two structures are not equal. + /// + /// The left hand operand. + /// The right hand operand. + /// + /// True if the parameter is not equal to the parameter; + /// otherwise, false. + /// + public static bool operator !=(TiffBitsPerSample left, TiffBitsPerSample right) => !(left == right); + /// /// Tries to parse a ushort array and convert it into a TiffBitsPerSample struct. /// diff --git a/src/ImageSharp/Formats/Tiff/TiffEncoderCore.cs b/src/ImageSharp/Formats/Tiff/TiffEncoderCore.cs index 16071001d5..9ccd4416fc 100644 --- a/src/ImageSharp/Formats/Tiff/TiffEncoderCore.cs +++ b/src/ImageSharp/Formats/Tiff/TiffEncoderCore.cs @@ -73,7 +73,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff /// private const TiffPhotometricInterpretation DefaultPhotometricInterpretation = TiffPhotometricInterpretation.Rgb; - private readonly List<(long, uint)> frameMarkers = new List<(long, uint)>(); + private readonly List<(long, uint)> frameMarkers = new(); /// /// Initializes a new instance of the class. @@ -148,15 +148,15 @@ namespace SixLabors.ImageSharp.Formats.Tiff // Make sure, the Encoder options makes sense in combination with each other. this.SanitizeAndSetEncoderOptions(bitsPerPixel, image.PixelType.BitsPerPixel, photometricInterpretation, compression, predictor); - using var writer = new TiffStreamWriter(stream); - long ifdMarker = this.WriteHeader(writer); + using TiffStreamWriter writer = new(stream); + long ifdMarker = WriteHeader(writer); Image metadataImage = image; foreach (ImageFrame frame in image.Frames) { cancellationToken.ThrowIfCancellationRequested(); - var subfileType = (TiffNewSubfileType)(frame.Metadata.ExifProfile?.GetValue(ExifTag.SubfileType)?.Value ?? (int)TiffNewSubfileType.FullImage); + TiffNewSubfileType subfileType = (TiffNewSubfileType)(frame.Metadata.ExifProfile?.GetValue(ExifTag.SubfileType)?.Value ?? (int)TiffNewSubfileType.FullImage); ifdMarker = this.WriteFrame(writer, frame, image.Metadata, metadataImage, ifdMarker); metadataImage = null; @@ -178,7 +178,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff /// /// The marker to write the first IFD offset. /// - public long WriteHeader(TiffStreamWriter writer) + public static long WriteHeader(TiffStreamWriter writer) { writer.Write(ByteOrderMarker); writer.Write(TiffConstants.HeaderMagicNumber); @@ -214,7 +214,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff this.compressionLevel, this.HorizontalPredictor == TiffPredictor.Horizontal ? this.HorizontalPredictor.Value : TiffPredictor.None); - var entriesCollector = new TiffEncoderEntriesCollector(); + TiffEncoderEntriesCollector entriesCollector = new(); using TiffBaseColorWriter colorWriter = TiffColorWriterFactory.Create( this.PhotometricInterpretation, frame, @@ -224,7 +224,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff entriesCollector, (int)this.BitsPerPixel); - int rowsPerStrip = this.CalcRowsPerStrip(frame.Height, colorWriter.BytesPerRow, this.CompressionType); + int rowsPerStrip = CalcRowsPerStrip(frame.Height, colorWriter.BytesPerRow, this.CompressionType); colorWriter.Write(compressor, rowsPerStrip); @@ -248,7 +248,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff /// The number of bytes per row. /// The compression used. /// Number of rows per strip. - private int CalcRowsPerStrip(int height, int bytesPerRow, TiffCompression? compression) + private static int CalcRowsPerStrip(int height, int bytesPerRow, TiffCompression? compression) { DebugGuard.MustBeGreaterThan(height, 0, nameof(height)); DebugGuard.MustBeGreaterThan(bytesPerRow, 0, nameof(bytesPerRow)); @@ -290,7 +290,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff } uint dataOffset = (uint)writer.Position + (uint)(6 + (entries.Count * 12)); - var largeDataBlocks = new List(); + List largeDataBlocks = new(); entries.Sort((a, b) => (ushort)a.Tag - (ushort)b.Tag); @@ -440,13 +440,6 @@ namespace SixLabors.ImageSharp.Formats.Tiff } public static bool IsOneBitCompression(TiffCompression? compression) - { - if (compression is TiffCompression.Ccitt1D or TiffCompression.CcittGroup3Fax or TiffCompression.CcittGroup4Fax) - { - return true; - } - - return false; - } + => compression is TiffCompression.Ccitt1D or TiffCompression.CcittGroup3Fax or TiffCompression.CcittGroup4Fax; } } diff --git a/src/ImageSharp/Formats/Tiff/Writers/TiffStreamWriter.cs b/src/ImageSharp/Formats/Tiff/Writers/TiffStreamWriter.cs index 667f75be43..d35d169488 100644 --- a/src/ImageSharp/Formats/Tiff/Writers/TiffStreamWriter.cs +++ b/src/ImageSharp/Formats/Tiff/Writers/TiffStreamWriter.cs @@ -28,7 +28,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Writers /// /// Gets a value indicating whether the architecture is little-endian. /// - public bool IsLittleEndian => BitConverter.IsLittleEndian; + public static bool IsLittleEndian => BitConverter.IsLittleEndian; /// /// Gets the current position within the stream. @@ -75,7 +75,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Writers /// The two-byte unsigned integer to write. public void Write(ushort value) { - if (this.IsLittleEndian) + if (IsLittleEndian) { BinaryPrimitives.WriteUInt16LittleEndian(this.buffer, value); } @@ -93,7 +93,7 @@ namespace SixLabors.ImageSharp.Formats.Tiff.Writers /// The four-byte unsigned integer to write. public void Write(uint value) { - if (this.IsLittleEndian) + if (IsLittleEndian) { BinaryPrimitives.WriteUInt32LittleEndian(this.buffer, value); } diff --git a/src/ImageSharp/Formats/Webp/BitReader/Vp8BitReader.cs b/src/ImageSharp/Formats/Webp/BitReader/Vp8BitReader.cs index 52e3907e96..24761213e8 100644 --- a/src/ImageSharp/Formats/Webp/BitReader/Vp8BitReader.cs +++ b/src/ImageSharp/Formats/Webp/BitReader/Vp8BitReader.cs @@ -133,7 +133,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitReader uint split = this.range >> 1; ulong value = this.value >> pos; ulong mask = (split - value) >> 31; // -1 or 0 - this.bits -= 1; + this.bits--; this.range = (this.range + (uint)mask) | 1; this.value -= ((split + 1) & mask) << pos; @@ -189,7 +189,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitReader { ulong inBits = BinaryPrimitives.ReadUInt64LittleEndian(this.Data.Memory.Span.Slice((int)this.pos, 8)); this.pos += BitsCount >> 3; - ulong bits = this.ByteSwap64(inBits); + ulong bits = ByteSwap64(inBits); bits >>= 64 - BitsCount; this.value = bits | (this.value << BitsCount); this.bits += BitsCount; @@ -221,7 +221,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitReader } [MethodImpl(InliningOptions.ShortMethod)] - private ulong ByteSwap64(ulong x) + private static ulong ByteSwap64(ulong x) { x = ((x & 0xffffffff00000000ul) >> 32) | ((x & 0x00000000fffffffful) << 32); x = ((x & 0xffff0000ffff0000ul) >> 16) | ((x & 0x0000ffff0000fffful) << 16); diff --git a/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs b/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs index 428403f606..ed41c29fe6 100644 --- a/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs +++ b/src/ImageSharp/Formats/Webp/BitWriter/BitWriterBase.cs @@ -5,7 +5,6 @@ using System; using System.Buffers.Binary; using System.IO; using SixLabors.ImageSharp.Metadata.Profiles.Exif; -using SixLabors.ImageSharp.Metadata.Profiles.Icc; using SixLabors.ImageSharp.Metadata.Profiles.Xmp; namespace SixLabors.ImageSharp.Formats.Webp.BitWriter @@ -38,6 +37,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitWriter /// Initializes a new instance of the class. /// Used internally for cloning. /// + /// The byte buffer. private protected BitWriterBase(byte[] buffer) => this.buffer = buffer; public byte[] Buffer => this.buffer; @@ -102,12 +102,10 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitWriter /// /// The metadata profile bytes. /// The metadata chunk size in bytes. - protected uint MetadataChunkSize(byte[] metadataBytes) + protected static uint MetadataChunkSize(byte[] metadataBytes) { uint metaSize = (uint)metadataBytes.Length; - uint metaChunkSize = WebpConstants.ChunkHeaderSize + metaSize + (metaSize & 1); - - return metaChunkSize; + return WebpConstants.ChunkHeaderSize + metaSize + (metaSize & 1); } /// @@ -115,12 +113,10 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitWriter /// /// The alpha chunk bytes. /// The alpha data chunk size in bytes. - protected uint AlphaChunkSize(Span alphaBytes) + protected static uint AlphaChunkSize(Span alphaBytes) { uint alphaSize = (uint)alphaBytes.Length + 1; - uint alphaChunkSize = WebpConstants.ChunkHeaderSize + alphaSize + (alphaSize & 1); - - return alphaChunkSize; + return WebpConstants.ChunkHeaderSize + alphaSize + (alphaSize & 1); } /// diff --git a/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs b/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs index 81cb9cc248..a218d50f4a 100644 --- a/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs +++ b/src/ImageSharp/Formats/Webp/BitWriter/Vp8BitWriter.cs @@ -433,27 +433,27 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitWriter { isVp8X = true; exifBytes = exifProfile.ToByteArray(); - riffSize += this.MetadataChunkSize(exifBytes); + riffSize += MetadataChunkSize(exifBytes); } if (xmpProfile != null) { isVp8X = true; xmpBytes = xmpProfile.Data; - riffSize += this.MetadataChunkSize(xmpBytes); + riffSize += MetadataChunkSize(xmpBytes); } if (iccProfile != null) { isVp8X = true; iccProfileBytes = iccProfile.ToByteArray(); - riffSize += this.MetadataChunkSize(iccProfileBytes); + riffSize += MetadataChunkSize(iccProfileBytes); } if (hasAlpha) { isVp8X = true; - riffSize += this.AlphaChunkSize(alphaData); + riffSize += AlphaChunkSize(alphaData); } if (isVp8X) diff --git a/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs b/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs index 78494004d3..cb4d6d6543 100644 --- a/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs +++ b/src/ImageSharp/Formats/Webp/BitWriter/Vp8LBitWriter.cs @@ -150,21 +150,21 @@ namespace SixLabors.ImageSharp.Formats.Webp.BitWriter { isVp8X = true; exifBytes = exifProfile.ToByteArray(); - riffSize += this.MetadataChunkSize(exifBytes); + riffSize += MetadataChunkSize(exifBytes); } if (xmpProfile != null) { isVp8X = true; xmpBytes = xmpProfile.Data; - riffSize += this.MetadataChunkSize(xmpBytes); + riffSize += MetadataChunkSize(xmpBytes); } if (iccProfile != null) { isVp8X = true; iccBytes = iccProfile.ToByteArray(); - riffSize += this.MetadataChunkSize(iccBytes); + riffSize += MetadataChunkSize(iccBytes); } if (isVp8X) diff --git a/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs b/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs index a09cdb8bcb..6e7cbd5e82 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/Vp8LEncoder.cs @@ -344,7 +344,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless foreach (CrunchConfig crunchConfig in crunchConfigs) { bgra.CopyTo(encodedData); - bool useCache = true; + const bool useCache = true; this.UsePalette = crunchConfig.EntropyIdx is EntropyIx.Palette or EntropyIx.PaletteAndSpatial; this.UseSubtractGreenTransform = crunchConfig.EntropyIdx is EntropyIx.SubGreen or EntropyIx.SpatialSubGreen; this.UsePredictorTransform = crunchConfig.EntropyIdx is EntropyIx.Spatial or EntropyIx.SpatialSubGreen; @@ -418,7 +418,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless if (isFirstConfig || this.bitWriter.NumBytes() < bestSize) { bestSize = this.bitWriter.NumBytes(); - this.BitWriterSwap(ref this.bitWriter, ref bitWriterBest); + BitWriterSwap(ref this.bitWriter, ref bitWriterBest); } // Reset the bit writer for the following iteration if any. @@ -430,7 +430,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless isFirstConfig = false; } - this.BitWriterSwap(ref bitWriterBest, ref this.bitWriter); + BitWriterSwap(ref bitWriterBest, ref this.bitWriter); } /// @@ -485,7 +485,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless EntropyIx entropyIdx = this.AnalyzeEntropy(bgra, width, height, usePalette, this.PaletteSize, this.TransformBits, out redAndBlueAlwaysZero); bool doNotCache = false; - var crunchConfigs = new List(); + List crunchConfigs = new(); if (this.method == WebpEncodingMethod.BestQuality && this.quality == 100) { @@ -540,7 +540,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless Span bgra = this.EncodedData.GetSpan(); int histogramImageXySize = LosslessUtils.SubSampleSize(width, this.HistoBits) * LosslessUtils.SubSampleSize(height, this.HistoBits); ushort[] histogramSymbols = new ushort[histogramImageXySize]; - var huffTree = new HuffmanTree[3 * WebpConstants.CodeLengthCodes]; + HuffmanTree[] huffTree = new HuffmanTree[3 * WebpConstants.CodeLengthCodes]; for (int i = 0; i < huffTree.Length; i++) { huffTree[i] = default; @@ -583,8 +583,8 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless Vp8LBackwardRefs refsTmp = this.Refs[refsBest.Equals(this.Refs[0]) ? 1 : 0]; this.bitWriter.Reset(bwInit); - var tmpHisto = new Vp8LHistogram(cacheBits); - var histogramImage = new List(histogramImageXySize); + Vp8LHistogram tmpHisto = new(cacheBits); + List histogramImage = new(histogramImageXySize); for (int i = 0; i < histogramImageXySize; i++) { histogramImage.Add(new Vp8LHistogram(cacheBits)); @@ -596,7 +596,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless // Create Huffman bit lengths and codes for each histogram image. int histogramImageSize = histogramImage.Count; int bitArraySize = 5 * histogramImageSize; - var huffmanCodes = new HuffmanTreeCode[bitArraySize]; + HuffmanTreeCode[] huffmanCodes = new HuffmanTreeCode[bitArraySize]; for (int i = 0; i < huffmanCodes.Length; i++) { huffmanCodes[i] = default; @@ -657,7 +657,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless } } - var tokens = new HuffmanTreeToken[maxTokens]; + HuffmanTreeToken[] tokens = new HuffmanTreeToken[maxTokens]; for (int i = 0; i < tokens.Length; i++) { tokens[i] = new HuffmanTreeToken(); @@ -767,13 +767,13 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless int cacheBits = 0; ushort[] histogramSymbols = new ushort[1]; // Only one tree, one symbol. - var huffmanCodes = new HuffmanTreeCode[5]; + HuffmanTreeCode[] huffmanCodes = new HuffmanTreeCode[5]; for (int i = 0; i < huffmanCodes.Length; i++) { huffmanCodes[i] = default; } - var huffTree = new HuffmanTree[3UL * WebpConstants.CodeLengthCodes]; + HuffmanTree[] huffTree = new HuffmanTree[3UL * WebpConstants.CodeLengthCodes]; for (int i = 0; i < huffTree.Length; i++) { huffTree[i] = default; @@ -794,7 +794,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless refsTmp1, refsTmp2); - var histogramImage = new List() + List histogramImage = new() { new(cacheBits) }; @@ -819,7 +819,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless } } - var tokens = new HuffmanTreeToken[maxTokens]; + HuffmanTreeToken[] tokens = new HuffmanTreeToken[maxTokens]; for (int i = 0; i < tokens.Length; i++) { tokens[i] = new HuffmanTreeToken(); @@ -842,8 +842,8 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless int count = 0; Span symbols = this.scratch.AsSpan(0, 2); symbols.Clear(); - int maxBits = 8; - int maxSymbol = 1 << maxBits; + const int maxBits = 8; + const int maxSymbol = 1 << maxBits; // Check whether it's a small tree. for (int i = 0; i < huffmanCode.NumSymbols && count < 3; i++) @@ -896,7 +896,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless int i; byte[] codeLengthBitDepth = new byte[WebpConstants.CodeLengthCodes]; short[] codeLengthBitDepthSymbols = new short[WebpConstants.CodeLengthCodes]; - var huffmanCode = new HuffmanTreeCode + HuffmanTreeCode huffmanCode = new() { NumSymbols = WebpConstants.CodeLengthCodes, CodeLengths = codeLengthBitDepth, @@ -1099,7 +1099,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless uint pix = currentRow[x]; uint pixDiff = LosslessUtils.SubPixels(pix, pixPrev); pixPrev = pix; - if (pixDiff == 0 || (prevRow != null && pix == prevRow[x])) + if (pixDiff == 0 || (prevRow.Length > 0 && pix == prevRow[x])) { continue; } @@ -1147,7 +1147,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless histo[(int)HistoIx.HistoBluePred * 256]++; histo[(int)HistoIx.HistoAlphaPred * 256]++; - var bitEntropy = new Vp8LBitEntropy(); + Vp8LBitEntropy bitEntropy = new(); for (int j = 0; j < (int)HistoIx.HistoTotal; j++) { bitEntropy.Init(); @@ -1239,7 +1239,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless private bool AnalyzeAndCreatePalette(ReadOnlySpan bgra, int width, int height) { Span palette = this.Palette.Memory.Span; - this.PaletteSize = this.GetColorPalette(bgra, width, height, palette); + this.PaletteSize = GetColorPalette(bgra, width, height, palette); if (this.PaletteSize > WebpConstants.MaxPaletteSize) { this.PaletteSize = 0; @@ -1265,9 +1265,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless /// The image height. /// The span to store the palette into. /// The number of palette entries. - private int GetColorPalette(ReadOnlySpan bgra, int width, int height, Span palette) + private static int GetColorPalette(ReadOnlySpan bgra, int width, int height, Span palette) { - var colors = new HashSet(); + HashSet colors = new(); for (int y = 0; y < height; y++) { ReadOnlySpan bgraRow = bgra.Slice(y * width, width); @@ -1547,7 +1547,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless /// True, if the palette has no monotonous deltas. private static bool PaletteHasNonMonotonousDeltas(Span palette, int numColors) { - uint predict = 0x000000; + const uint predict = 0x000000; byte signFound = 0x00; for (int i = 0; i < numColors; i++) { @@ -1637,7 +1637,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless // Create Huffman trees. bool[] bufRle = new bool[maxNumSymbols]; - var huffTree = new HuffmanTree[3 * maxNumSymbols]; + HuffmanTree[] huffTree = new HuffmanTree[3 * maxNumSymbols]; for (int i = 0; i < huffTree.Length; i++) { huffTree[i] = default; @@ -1665,7 +1665,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless private static uint PaletteColorDistance(uint col1, uint col2) { uint diff = LosslessUtils.SubPixels(col1, col2); - uint moreWeightForRGBThanForAlpha = 9; + const uint moreWeightForRGBThanForAlpha = 9; uint score = PaletteComponentDistance((diff >> 0) & 0xff); score += PaletteComponentDistance((diff >> 8) & 0xff); score += PaletteComponentDistance((diff >> 16) & 0xff); @@ -1730,7 +1730,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless } [MethodImpl(InliningOptions.ShortMethod)] - private void BitWriterSwap(ref Vp8LBitWriter src, ref Vp8LBitWriter dst) + private static void BitWriterSwap(ref Vp8LBitWriter src, ref Vp8LBitWriter dst) { Vp8LBitWriter tmp = src; src = dst; diff --git a/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs b/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs index fafd5b49ca..b90dbf4dbb 100644 --- a/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossless/WebpLosslessDecoder.cs @@ -96,7 +96,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless public void Decode(Buffer2D pixels, int width, int height) where TPixel : unmanaged, IPixel { - using (var decoder = new Vp8LDecoder(width, height, this.memoryAllocator)) + using (Vp8LDecoder decoder = new(width, height, this.memoryAllocator)) { this.DecodeImageStream(decoder, width, height, true); this.DecodeImageData(decoder, decoder.Pixels.Memory.Span); @@ -169,7 +169,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless decoder.Metadata.ColorCacheSize = 0; } - this.UpdateDecoder(decoder, transformXSize, transformYSize); + UpdateDecoder(decoder, transformXSize, transformYSize); if (isLevel0) { // level 0 complete. @@ -207,7 +207,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless public void DecodeImageData(Vp8LDecoder decoder, Span pixelData) { - int lastPixel = 0; + const int lastPixel = 0; int width = decoder.Width; int height = decoder.Height; int row = lastPixel / width; @@ -233,7 +233,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless if (hTreeGroup[0].IsTrivialCode) { pixelData[decodedPixels] = hTreeGroup[0].LiteralArb; - this.AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); + AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); continue; } @@ -248,7 +248,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless if (code == PackedNonLiteralCode) { - this.AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); + AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); continue; } } @@ -283,7 +283,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless pixelData[decodedPixels] = (uint)(((byte)alpha << 24) | ((byte)red << 16) | ((byte)code << 8) | (byte)blue); } - this.AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); + AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); } else if (code < lenCodeLimit) { @@ -333,7 +333,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless } pixelData[decodedPixels] = colorCache.Lookup(key); - this.AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); + AdvanceByOne(ref col, ref row, width, colorCache, ref decodedPixels, pixelData, ref lastCached); } else { @@ -342,7 +342,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless } } - private void AdvanceByOne(ref int col, ref int row, int width, ColorCache colorCache, ref int decodedPixels, Span pixelData, ref int lastCached) + private static void AdvanceByOne(ref int col, ref int row, int width, ColorCache colorCache, ref int decodedPixels, Span pixelData, ref int lastCached) { col++; decodedPixels++; @@ -414,8 +414,8 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless } int tableSize = TableSize[colorCacheBits]; - var huffmanTables = new HuffmanCode[numHTreeGroups * tableSize]; - var hTreeGroups = new HTreeGroup[numHTreeGroups]; + HuffmanCode[] huffmanTables = new HuffmanCode[numHTreeGroups * tableSize]; + HTreeGroup[] hTreeGroups = new HTreeGroup[numHTreeGroups]; Span huffmanTable = huffmanTables.AsSpan(); int[] codeLengths = new int[maxAlphabetSize]; for (int i = 0; i < numHTreeGroupsMax; i++) @@ -488,7 +488,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless hTreeGroup.UsePackedTable = !hTreeGroup.IsTrivialCode && maxBits < HuffmanUtils.HuffmanPackedBits; if (hTreeGroup.UsePackedTable) { - this.BuildPackedTable(hTreeGroup); + BuildPackedTable(hTreeGroup); } } @@ -546,9 +546,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless this.ReadHuffmanCodeLengths(table, codeLengthCodeLengths, alphabetSize, codeLengths); } - int size = HuffmanUtils.BuildHuffmanTable(table, HuffmanUtils.HuffmanTableBits, codeLengths, alphabetSize); - - return size; + return HuffmanUtils.BuildHuffmanTable(table, HuffmanUtils.HuffmanTableBits, codeLengths, alphabetSize); } private void ReadHuffmanCodeLengths(Span table, int[] codeLengthCodeLengths, int numSymbols, int[] codeLengths) @@ -622,8 +620,8 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless /// Vp8LDecoder where the transformations will be stored. private void ReadTransformation(int xSize, int ySize, Vp8LDecoder decoder) { - var transformType = (Vp8LTransformType)this.bitReader.ReadValue(2); - var transform = new Vp8LTransform(transformType, xSize, ySize); + Vp8LTransformType transformType = (Vp8LTransformType)this.bitReader.ReadValue(2); + Vp8LTransform transform = new(transformType, xSize, ySize); // Each transform is allowed to be used only once. foreach (Vp8LTransform decoderTransform in decoder.Transforms) @@ -643,11 +641,23 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless // The transform data contains color table size and the entries in the color table. // 8 bit value for color table size. uint numColors = this.bitReader.ReadValue(8) + 1; - int bits = numColors > 16 ? 0 - : numColors > 4 ? 1 - : numColors > 2 ? 2 - : 3; - transform.Bits = bits; + if (numColors > 16) + { + transform.Bits = 0; + } + else if (numColors > 4) + { + transform.Bits = 1; + } + else if (numColors > 2) + { + transform.Bits = 2; + } + else + { + transform.Bits = 3; + } + using (IMemoryOwner colorMap = this.DecodeImageStream(decoder, (int)numColors, 1, false)) { int finalNumColors = 1 << (8 >> transform.Bits); @@ -660,15 +670,13 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless case Vp8LTransformType.PredictorTransform: case Vp8LTransformType.CrossColorTransform: - { + // The first 3 bits of prediction data define the block width and height in number of bits. transform.Bits = (int)this.bitReader.ReadValue(3) + 2; int blockWidth = LosslessUtils.SubSampleSize(transform.XSize, transform.Bits); int blockHeight = LosslessUtils.SubSampleSize(transform.YSize, transform.Bits); - IMemoryOwner transformData = this.DecodeImageStream(decoder, blockWidth, blockHeight, false); - transform.Data = transformData; + transform.Data = this.DecodeImageStream(decoder, blockWidth, blockHeight, false); break; - } } decoder.Transforms.Add(transform); @@ -687,8 +695,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless for (int i = transforms.Count - 1; i >= 0; i--) { Vp8LTransform transform = transforms[i]; - Vp8LTransformType transformType = transform.TransformType; - switch (transformType) + switch (transform.TransformType) { case Vp8LTransformType.PredictorTransform: using (IMemoryOwner output = memoryAllocator.Allocate(pixelData.Length, AllocationOptions.Clean)) @@ -806,7 +813,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless dec.ExtractPalettedAlphaRows(row > lastRow ? lastRow : row); } - private void UpdateDecoder(Vp8LDecoder decoder, int width, int height) + private static void UpdateDecoder(Vp8LDecoder decoder, int width, int height) { int numBits = decoder.Metadata.HuffmanSubSampleBits; decoder.Width = width; @@ -831,7 +838,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless return code.Value; } - private void BuildPackedTable(HTreeGroup hTreeGroup) + private static void BuildPackedTable(HTreeGroup hTreeGroup) { for (uint code = 0; code < HuffmanUtils.HuffmanPackedTableSize; code++) { @@ -859,6 +866,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossless /// Decodes the next Huffman code from the bit-stream. /// FillBitWindow() needs to be called at minimum every second call to ReadSymbol, in order to pre-fetch enough bits. /// + /// The Huffman table. private uint ReadSymbol(Span table) { uint val = (uint)this.bitReader.PrefetchBits(); diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncIterator.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncIterator.cs index 0043d6d281..3092e01e33 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8EncIterator.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8EncIterator.cs @@ -34,7 +34,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy /// private readonly int predsWidth; - // Array to record the position of the top sample to pass to the prediction functions. + /// + /// Array to record the position of the top sample to pass to the prediction functions. + /// private readonly byte[] vp8TopLeftI4 = { 17, 21, 25, 29, @@ -46,9 +48,6 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy private int currentMbIdx; private int nzIdx; - - private int predIdx; - private int yTopIdx; private int uvTopIdx; @@ -69,7 +68,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy this.yTopIdx = 0; this.uvTopIdx = 0; this.predsWidth = (4 * mbw) + 1; - this.predIdx = this.predsWidth; + this.PredIdx = this.predsWidth; this.YuvIn = new byte[WebpConstants.Bps * 16]; this.YuvOut = new byte[WebpConstants.Bps * 16]; this.YuvOut2 = new byte[WebpConstants.Bps * 16]; @@ -85,7 +84,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy this.Scratch3 = new int[16]; // To match the C initial values of the reference implementation, initialize all with 204. - byte defaultInitVal = 204; + const byte defaultInitVal = 204; this.YuvIn.AsSpan().Fill(defaultInitVal); this.YuvOut.AsSpan().Fill(defaultInitVal); this.YuvOut2.AsSpan().Fill(defaultInitVal); @@ -160,7 +159,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy /// /// Gets the current start index of the intra mode predictors. /// - public int PredIdx => this.predIdx; + public int PredIdx { get; private set; } /// /// Gets the non-zero pattern. @@ -238,7 +237,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy public void Init() => this.Reset(); - public void InitFilter() + public static void InitFilter() { // TODO: add support for autofilter } @@ -299,9 +298,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy Span yuvIn = this.YuvIn.AsSpan(YOffEnc); Span uIn = this.YuvIn.AsSpan(UOffEnc); Span vIn = this.YuvIn.AsSpan(VOffEnc); - this.ImportBlock(ySrc, yStride, yuvIn, w, h, 16); - this.ImportBlock(uSrc, uvStride, uIn, uvw, uvh, 8); - this.ImportBlock(vSrc, uvStride, vIn, uvw, uvh, 8); + ImportBlock(ySrc, yStride, yuvIn, w, h, 16); + ImportBlock(uSrc, uvStride, uIn, uvw, uvh, 8); + ImportBlock(vSrc, uvStride, vIn, uvw, uvh, 8); if (!importBoundarySamples) { @@ -331,9 +330,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy vLeft[0] = v[uvStartIdx - 1 - uvStride]; } - this.ImportLine(y[(yStartIdx - 1)..], yStride, yLeft[1..], h, 16); - this.ImportLine(u[(uvStartIdx - 1)..], uvStride, uLeft[1..], uvh, 8); - this.ImportLine(v[(uvStartIdx - 1)..], uvStride, vLeft[1..], uvh, 8); + ImportLine(y[(yStartIdx - 1)..], yStride, yLeft[1..], h, 16); + ImportLine(u[(uvStartIdx - 1)..], uvStride, uLeft[1..], uvh, 8); + ImportLine(v[(uvStartIdx - 1)..], uvStride, vLeft[1..], uvh, 8); } Span yTop = this.YTop.AsSpan(this.yTopIdx, 16); @@ -344,9 +343,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } else { - this.ImportLine(y[(yStartIdx - yStride)..], 1, yTop, w, 16); - this.ImportLine(u[(uvStartIdx - uvStride)..], 1, this.UvTop.AsSpan(this.uvTopIdx, 8), uvw, 8); - this.ImportLine(v[(uvStartIdx - uvStride)..], 1, this.UvTop.AsSpan(this.uvTopIdx + 8, 8), uvw, 8); + ImportLine(y[(yStartIdx - yStride)..], 1, yTop, w, 16); + ImportLine(u[(uvStartIdx - uvStride)..], 1, this.UvTop.AsSpan(this.uvTopIdx, 8), uvw, 8); + ImportLine(v[(uvStartIdx - uvStride)..], 1, this.UvTop.AsSpan(this.uvTopIdx + 8, 8), uvw, 8); } } @@ -386,7 +385,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy public int MbAnalyzeBestIntra16Mode() { - int maxMode = MaxIntra16Mode; + const int maxMode = MaxIntra16Mode; int mode; int bestAlpha = DefaultAlpha; int bestMode = 0; @@ -394,7 +393,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy this.MakeLuma16Preds(); for (mode = 0; mode < maxMode; mode++) { - var histo = new Vp8Histogram(); + Vp8Histogram histo = new(); histo.CollectHistogram(this.YuvIn.AsSpan(YOffEnc), this.YuvP.AsSpan(Vp8Encoding.Vp8I16ModeOffsets[mode]), 0, 16); int alpha = histo.GetAlpha(); if (alpha > bestAlpha) @@ -411,15 +410,15 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy public int MbAnalyzeBestIntra4Mode(int bestAlpha) { byte[] modes = new byte[16]; - int maxMode = MaxIntra4Mode; - var totalHisto = new Vp8Histogram(); + const int maxMode = MaxIntra4Mode; + Vp8Histogram totalHisto = new(); int curHisto = 0; this.StartI4(); do { int mode; int bestModeAlpha = DefaultAlpha; - var histos = new Vp8Histogram[2]; + Vp8Histogram[] histos = new Vp8Histogram[2]; Span src = this.YuvIn.AsSpan(YOffEnc + WebpLookupTables.Vp8Scan[this.I4]); this.MakeIntra4Preds(); @@ -459,13 +458,13 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy int bestAlpha = DefaultAlpha; int smallestAlpha = 0; int bestMode = 0; - int maxMode = MaxUvMode; + const int maxMode = MaxUvMode; int mode; this.MakeChroma8Preds(); for (mode = 0; mode < maxMode; ++mode) { - var histo = new Vp8Histogram(); + Vp8Histogram histo = new(); histo.CollectHistogram(this.YuvIn.AsSpan(UOffEnc), this.YuvP.AsSpan(Vp8Encoding.Vp8UvModeOffsets[mode]), 16, 16 + 4 + 4); int alpha = histo.GetAlpha(); if (alpha > bestAlpha) @@ -487,7 +486,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy public void SetIntra16Mode(int mode) { - Span preds = this.Preds.AsSpan(this.predIdx); + Span preds = this.Preds.AsSpan(this.PredIdx); for (int y = 0; y < 4; y++) { preds[..4].Fill((byte)mode); @@ -500,7 +499,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy public void SetIntra4Mode(byte[] modes) { int modesIdx = 0; - int predIdx = this.predIdx; + int predIdx = this.PredIdx; for (int y = 4; y > 0; y--) { modes.AsSpan(modesIdx, 4).CopyTo(this.Preds.AsSpan(predIdx)); @@ -542,7 +541,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy public short[] GetCostModeI4(byte[] modes) { int predsWidth = this.predsWidth; - int predIdx = this.predIdx; + int predIdx = this.PredIdx; int x = this.I4 & 3; int y = this.I4 >> 2; int left = x == 0 ? this.Preds[predIdx + (y * predsWidth) - 1] : modes[this.I4 - 1]; @@ -635,7 +634,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy { this.currentMbIdx++; this.nzIdx++; - this.predIdx += 4; + this.PredIdx += 4; this.yTopIdx += 16; this.uvTopIdx += 16; } @@ -772,35 +771,35 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy Span leftNz = this.LeftNz; // Top-Y - topNz[0] = this.Bit(tnz, 12); - topNz[1] = this.Bit(tnz, 13); - topNz[2] = this.Bit(tnz, 14); - topNz[3] = this.Bit(tnz, 15); + topNz[0] = Bit(tnz, 12); + topNz[1] = Bit(tnz, 13); + topNz[2] = Bit(tnz, 14); + topNz[3] = Bit(tnz, 15); // Top-U - topNz[4] = this.Bit(tnz, 18); - topNz[5] = this.Bit(tnz, 19); + topNz[4] = Bit(tnz, 18); + topNz[5] = Bit(tnz, 19); // Top-V - topNz[6] = this.Bit(tnz, 22); - topNz[7] = this.Bit(tnz, 23); + topNz[6] = Bit(tnz, 22); + topNz[7] = Bit(tnz, 23); // DC - topNz[8] = this.Bit(tnz, 24); + topNz[8] = Bit(tnz, 24); // left-Y - leftNz[0] = this.Bit(lnz, 3); - leftNz[1] = this.Bit(lnz, 7); - leftNz[2] = this.Bit(lnz, 11); - leftNz[3] = this.Bit(lnz, 15); + leftNz[0] = Bit(lnz, 3); + leftNz[1] = Bit(lnz, 7); + leftNz[2] = Bit(lnz, 11); + leftNz[3] = Bit(lnz, 15); // left-U - leftNz[4] = this.Bit(lnz, 17); - leftNz[5] = this.Bit(lnz, 19); + leftNz[4] = Bit(lnz, 17); + leftNz[5] = Bit(lnz, 19); // left-V - leftNz[6] = this.Bit(lnz, 21); - leftNz[7] = this.Bit(lnz, 23); + leftNz[6] = Bit(lnz, 21); + leftNz[7] = Bit(lnz, 23); // left-DC is special, iterated separately. } @@ -826,7 +825,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy this.Nz[this.nzIdx] = nz; } - private void ImportBlock(Span src, int srcStride, Span dst, int w, int h, int size) + private static void ImportBlock(Span src, int srcStride, Span dst, int w, int h, int size) { int dstIdx = 0; int srcIdx = 0; @@ -852,7 +851,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } } - private void ImportLine(Span src, int srcStride, Span dst, int len, int totalLen) + private static void ImportLine(Span src, int srcStride, Span dst, int len, int totalLen) { int i; int srcIdx = 0; @@ -892,7 +891,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy this.nzIdx = 1; // note: in reference source nz starts at -1. this.yTopIdx = 0; this.uvTopIdx = 0; - this.predIdx = this.predsWidth + (y * 4 * this.predsWidth); + this.PredIdx = this.predsWidth + (y * 4 * this.predsWidth); this.InitLeft(); } @@ -931,7 +930,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy this.TopDerr.AsSpan().Clear(); } - private int Bit(uint nz, int n) => (nz & (1 << n)) != 0 ? 1 : 0; + private static int Bit(uint nz, int n) => (nz & (1 << n)) != 0 ? 1 : 0; /// /// Set count down. diff --git a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs index 9dbbccbc74..12b2ea7dc2 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/Vp8Encoder.cs @@ -123,10 +123,22 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy this.filterStrength = Numerics.Clamp(filterStrength, 0, 100); this.spatialNoiseShaping = Numerics.Clamp(spatialNoiseShaping, 0, 100); this.alphaCompression = alphaCompression; - this.rdOptLevel = method is WebpEncodingMethod.BestQuality ? Vp8RdLevel.RdOptTrellisAll - : method >= WebpEncodingMethod.Level5 ? Vp8RdLevel.RdOptTrellis - : method >= WebpEncodingMethod.Level3 ? Vp8RdLevel.RdOptBasic - : Vp8RdLevel.RdOptNone; + if (method is WebpEncodingMethod.BestQuality) + { + this.rdOptLevel = Vp8RdLevel.RdOptTrellisAll; + } + else if (method >= WebpEncodingMethod.Level5) + { + this.rdOptLevel = Vp8RdLevel.RdOptTrellis; + } + else if (method >= WebpEncodingMethod.Level3) + { + this.rdOptLevel = Vp8RdLevel.RdOptBasic; + } + else + { + this.rdOptLevel = Vp8RdLevel.RdOptNone; + } int pixelCount = width * height; this.Mbw = (width + 15) >> 4; @@ -142,7 +154,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy this.TopDerr = new sbyte[this.Mbw * 4]; // TODO: make partition_limit configurable? - int limit = 100; // original code: limit = 100 - config->partition_limit; + const int limit = 100; // original code: limit = 100 - config->partition_limit; this.maxI4HeaderBits = 256 * 16 * 16 * limit * limit / (100 * 100); // ... modulated with a quadratic curve. @@ -307,7 +319,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy int yStride = width; int uvStride = (yStride + 1) >> 1; - var it = new Vp8EncIterator(this.YTop, this.UvTop, this.Nz, this.MbInfo, this.Preds, this.TopDerr, this.Mbw, this.Mbh); + Vp8EncIterator it = new(this.YTop, this.UvTop, this.Nz, this.MbInfo, this.Preds, this.TopDerr, this.Mbw, this.Mbh); int[] alphas = new int[WebpConstants.MaxAlpha + 1]; this.alpha = this.MacroBlockAnalysis(width, height, it, y, u, v, yStride, uvStride, alphas, out this.uvAlpha); int totalMb = this.Mbw * this.Mbw; @@ -327,7 +339,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy // Extract and encode alpha channel data, if present. int alphaDataSize = 0; bool alphaCompressionSucceeded = false; - using var alphaEncoder = new AlphaEncoder(); + using AlphaEncoder alphaEncoder = new(); Span alphaData = Span.Empty; if (hasAlpha) { @@ -344,9 +356,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy // Stats-collection loop. this.StatLoop(width, height, yStride, uvStride); it.Init(); - it.InitFilter(); - var info = new Vp8ModeScore(); - var residual = new Vp8Residual(); + Vp8EncIterator.InitFilter(); + Vp8ModeScore info = new(); + Vp8Residual residual = new(); do { bool dontUseSkip = !this.Proba.UseSkipProba; @@ -399,17 +411,21 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy /// This is used for deciding optimal probabilities. It also modifies the /// quantizer value if some target (size, PSNR) was specified. /// + /// The image width. + /// The image height. + /// The y-luminance stride. + /// The uv stride. private void StatLoop(int width, int height, int yStride, int uvStride) { - int targetSize = 0; // TODO: target size is hardcoded. - float targetPsnr = 0.0f; // TODO: targetPsnr is hardcoded. - bool doSearch = targetSize > 0 || targetPsnr > 0; + const int targetSize = 0; // TODO: target size is hardcoded. + const float targetPsnr = 0.0f; // TODO: targetPsnr is hardcoded. + const bool doSearch = targetSize > 0 || targetPsnr > 0; bool fastProbe = (this.method == 0 || this.method == WebpEncodingMethod.Level3) && !doSearch; int numPassLeft = this.entropyPasses; Vp8RdLevel rdOpt = this.method >= WebpEncodingMethod.Level3 || doSearch ? Vp8RdLevel.RdOptBasic : Vp8RdLevel.RdOptNone; int nbMbs = this.Mbw * this.Mbh; - var stats = new PassStats(targetSize, targetPsnr, QMin, QMax, this.quality); + PassStats stats = new(targetSize, targetPsnr, QMin, QMax, this.quality); this.Proba.ResetTokenStats(); // Fast mode: quick analysis pass over few mbs. Better than nothing. @@ -450,7 +466,10 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy // If no target size: just do several pass without changing 'q' if (doSearch) { + // Unreachable due to hardcoding above. +#pragma warning disable CS0162 // Unreachable code detected stats.ComputeNextQ(); +#pragma warning restore CS0162 // Unreachable code detected if (MathF.Abs(stats.Dq) <= DqLimit) { break; @@ -474,7 +493,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy Span y = this.Y.GetSpan(); Span u = this.U.GetSpan(); Span v = this.V.GetSpan(); - var it = new Vp8EncIterator(this.YTop, this.UvTop, this.Nz, this.MbInfo, this.Preds, this.TopDerr, this.Mbw, this.Mbh); + Vp8EncIterator it = new(this.YTop, this.UvTop, this.Nz, this.MbInfo, this.Preds, this.TopDerr, this.Mbw, this.Mbh); long size = 0; long sizeP0 = 0; long distortion = 0; @@ -482,7 +501,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy it.Init(); this.SetLoopParams(stats.Q); - var info = new Vp8ModeScore(); + Vp8ModeScore info = new(); do { info.Clear(); @@ -540,7 +559,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy // this '>> 3' accounts for some inverse WHT scaling int delta = (dqm.MaxEdge * dqm.Y2.Q[1]) >> 3; - int level = this.FilterStrengthFromDelta(this.FilterHeader.Sharpness, delta); + int level = FilterStrengthFromDelta(this.FilterHeader.Sharpness, delta); if (level > dqm.FStrength) { dqm.FStrength = level; @@ -757,8 +776,8 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy private void SetupFilterStrength() { - int filterSharpness = 0; // TODO: filterSharpness is hardcoded - int filterType = 1; // TODO: filterType is hardcoded + const int filterSharpness = 0; // TODO: filterSharpness is hardcoded + const int filterType = 1; // TODO: filterType is hardcoded // level0 is in [0..500]. Using '-f 50' as filter_strength is mid-filtering. int level0 = 5 * this.filterStrength; @@ -768,11 +787,22 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy // We focus on the quantization of AC coeffs. int qstep = WebpLookupTables.AcTable[Numerics.Clamp(m.Quant, 0, 127)] >> 2; - int baseStrength = this.FilterStrengthFromDelta(this.FilterHeader.Sharpness, qstep); + int baseStrength = FilterStrengthFromDelta(this.FilterHeader.Sharpness, qstep); // Segments with lower complexity ('beta') will be less filtered. int f = baseStrength * level0 / (256 + m.Beta); - m.FStrength = f < WebpConstants.FilterStrengthCutoff ? 0 : f > 63 ? 63 : f; + if (f < WebpConstants.FilterStrengthCutoff) + { + m.FStrength = 0; + } + else if (f > 63) + { + m.FStrength = 63; + } + else + { + m.FStrength = f; + } } // We record the initial strength (mainly for the case of 1-segment only). @@ -1027,10 +1057,12 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy /// Same as CodeResiduals, but doesn't actually write anything. /// Instead, it just records the event distribution. /// + /// The iterator. + /// The score accumulator. private void RecordResiduals(Vp8EncIterator it, Vp8ModeScore rd) { int x, y, ch; - var residual = new Vp8Residual(); + Vp8Residual residual = new(); bool i16 = it.CurrentMacroBlockInfo.MacroBlockType == Vp8MacroBlockType.I16X16; it.NzToBytes(); @@ -1096,6 +1128,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy /// is around q=75. Internally, our "good" middle is around c=50. So we /// map accordingly using linear piece-wise function /// + /// The compression level. [MethodImpl(InliningOptions.ShortMethod)] private static double QualityToCompression(double c) { @@ -1107,13 +1140,11 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy // this power-law: quant ~= compression ^ 1/3. This law holds well for // low quant. Finer modeling for high-quant would make use of AcTable[] // more explicitly. - double v = Math.Pow(linearC, 1 / 3.0d); - - return v; + return (double)Math.Pow(linearC, 1 / 3.0d); } [MethodImpl(InliningOptions.ShortMethod)] - private int FilterStrengthFromDelta(int sharpness, int delta) + private static int FilterStrengthFromDelta(int sharpness, int delta) { int pos = delta < WebpConstants.MaxDelzaSize ? delta : WebpConstants.MaxDelzaSize - 1; return WebpLookupTables.LevelsFromDelta[sharpness, pos]; diff --git a/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs b/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs index b290ee58bf..e913e98989 100644 --- a/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs +++ b/src/ImageSharp/Formats/Webp/Lossy/WebpLossyDecoder.cs @@ -72,7 +72,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy // Paragraph 9.2: color space and clamp type follow. sbyte colorSpace = (sbyte)this.bitReader.ReadValue(1); sbyte clampType = (sbyte)this.bitReader.ReadValue(1); - var pictureHeader = new Vp8PictureHeader() + Vp8PictureHeader pictureHeader = new() { Width = (uint)width, Height = (uint)height, @@ -83,10 +83,10 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy }; // Paragraph 9.3: Parse the segment header. - var proba = new Vp8Proba(); + Vp8Proba proba = new(); Vp8SegmentHeader vp8SegmentHeader = this.ParseSegmentHeader(proba); - using (var decoder = new Vp8Decoder(info.Vp8FrameHeader, pictureHeader, vp8SegmentHeader, proba, this.memoryAllocator)) + using (Vp8Decoder decoder = new(info.Vp8FrameHeader, pictureHeader, vp8SegmentHeader, proba, this.memoryAllocator)) { Vp8Io io = InitializeVp8Io(decoder, pictureHeader); @@ -111,7 +111,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy if (info.Features?.Alpha == true) { - using (var alphaDecoder = new AlphaDecoder( + using (AlphaDecoder alphaDecoder = new( width, height, alphaData, @@ -120,7 +120,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy this.configuration)) { alphaDecoder.Decode(); - this.DecodePixelValues(width, height, decoder.Pixels.Memory.Span, pixels, alphaDecoder.Alpha); + DecodePixelValues(width, height, decoder.Pixels.Memory.Span, pixels, alphaDecoder.Alpha); } } else @@ -146,7 +146,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } } - private void DecodePixelValues(int width, int height, Span pixelData, Buffer2D decodedPixels, IMemoryOwner alpha) + private static void DecodePixelValues(int width, int height, Span pixelData, Buffer2D decodedPixels, IMemoryOwner alpha) where TPixel : unmanaged, IPixel { TPixel color = default; @@ -187,7 +187,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } // Prepare for next scanline. - this.InitScanline(dec); + InitScanline(dec); // Reconstruct, filter and emit the row. this.ProcessRow(dec, io); @@ -222,9 +222,27 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy if (!block.IsI4x4) { // Hardcoded 16x16 intra-mode decision tree. - int yMode = this.bitReader.GetBit(156) != 0 ? - this.bitReader.GetBit(128) != 0 ? (int)IntraPredictionMode.TrueMotion : (int)IntraPredictionMode.HPrediction : - this.bitReader.GetBit(163) != 0 ? (int)IntraPredictionMode.VPrediction : (int)IntraPredictionMode.DcPrediction; + int yMode; + if (this.bitReader.GetBit(156) != 0) + { + if (this.bitReader.GetBit(128) != 0) + { + yMode = (int)IntraPredictionMode.TrueMotion; + } + else + { + yMode = (int)IntraPredictionMode.HPrediction; + } + } + else if (this.bitReader.GetBit(163) != 0) + { + yMode = (int)IntraPredictionMode.VPrediction; + } + else + { + yMode = (int)IntraPredictionMode.DcPrediction; + } + block.Modes[0] = (byte)yMode; for (int i = 0; i < left.Length; i++) { @@ -258,12 +276,29 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } // Hardcoded UVMode decision tree. - block.UvMode = (byte)(this.bitReader.GetBit(142) == 0 ? 0 : - this.bitReader.GetBit(114) == 0 ? 2 : - this.bitReader.GetBit(183) != 0 ? 1 : 3); + if (this.bitReader.GetBit(142) == 0) + { + // Hardcoded UVMode decision tree. + block.UvMode = 0; + } + else if (this.bitReader.GetBit(114) == 0) + { + // Hardcoded UVMode decision tree. + block.UvMode = 2; + } + else if (this.bitReader.GetBit(183) != 0) + { + // Hardcoded UVMode decision tree. + block.UvMode = 1; + } + else + { + // Hardcoded UVMode decision tree. + block.UvMode = 3; + } } - private void InitScanline(Vp8Decoder dec) + private static void InitScanline(Vp8Decoder dec) { Vp8MacroBlock left = dec.LeftMacroBlock; left.NoneZeroAcDcCoeffs = 0; @@ -279,7 +314,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy private void ProcessRow(Vp8Decoder dec, Vp8Io io) { this.ReconstructRow(dec); - this.FinishRow(dec, io); + FinishRow(dec, io); } private void ReconstructRow(Vp8Decoder dec) @@ -404,8 +439,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy { int offset = yOff + WebpConstants.Scan[n]; Span dst = yuv[offset..]; - byte lumaMode = block.Modes[n]; - switch (lumaMode) + switch (block.Modes[n]) { case 0: LossyUtils.DC4(dst, yuv, offset); @@ -439,14 +473,13 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy break; } - this.DoTransform(bits, coeffs.AsSpan(n * 16), dst, this.scratch); + DoTransform(bits, coeffs.AsSpan(n * 16), dst, this.scratch); } } else { // 16x16 - int mode = CheckMode(mbx, mby, block.Modes[0]); - switch (mode) + switch (CheckMode(mbx, mby, block.Modes[0])) { case 0: LossyUtils.DC16(yDst, yuv, yOff); @@ -475,15 +508,14 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy { for (int n = 0; n < 16; ++n, bits <<= 2) { - this.DoTransform(bits, coeffs.AsSpan(n * 16), yDst[WebpConstants.Scan[n]..], this.scratch); + DoTransform(bits, coeffs.AsSpan(n * 16), yDst[WebpConstants.Scan[n]..], this.scratch); } } } // Chroma uint bitsUv = block.NonZeroUv; - int chromaMode = CheckMode(mbx, mby, block.UvMode); - switch (chromaMode) + switch (CheckMode(mbx, mby, block.UvMode)) { case 0: LossyUtils.DC8uv(uDst, yuv, uOff); @@ -515,8 +547,8 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy break; } - this.DoUVTransform(bitsUv, coeffs.AsSpan(16 * 16), uDst, this.scratch); - this.DoUVTransform(bitsUv >> 8, coeffs.AsSpan(20 * 16), vDst, this.scratch); + DoUVTransform(bitsUv, coeffs.AsSpan(16 * 16), uDst, this.scratch); + DoUVTransform(bitsUv >> 8, coeffs.AsSpan(20 * 16), vDst, this.scratch); // Stash away top samples for next block. if (mby < dec.MbHeight - 1) @@ -544,16 +576,16 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } } - private void FilterRow(Vp8Decoder dec) + private static void FilterRow(Vp8Decoder dec) { int mby = dec.MbY; for (int mbx = dec.TopLeftMbX; mbx < dec.BottomRightMbX; ++mbx) { - this.DoFilter(dec, mbx, mby); + DoFilter(dec, mbx, mby); } } - private void DoFilter(Vp8Decoder dec, int mbx, int mby) + private static void DoFilter(Vp8Decoder dec, int mbx, int mby) { int yBps = dec.CacheYStride; Vp8FilterInfo filterInfo = dec.FilterInfo[mbx]; @@ -620,7 +652,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } } - private void FinishRow(Vp8Decoder dec, Vp8Io io) + private static void FinishRow(Vp8Decoder dec, Vp8Io io) { int extraYRows = WebpConstants.FilterExtraRows[(int)dec.Filter]; int ySize = extraYRows * dec.CacheYStride; @@ -635,7 +667,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy if (filterRow) { - this.FilterRow(dec); + FilterRow(dec); } int yStart = mby * 16; @@ -669,7 +701,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy io.MbY = yStart; io.MbW = io.Width; io.MbH = yEnd - yStart; - this.EmitRgb(dec, io); + EmitRgb(dec, io); } // Rotate top samples if needed. @@ -681,7 +713,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } } - private int EmitRgb(Vp8Decoder dec, Vp8Io io) + private static int EmitRgb(Vp8Decoder dec, Vp8Io io) { Span buf = dec.Pixels.Memory.Span; int numLinesOut = io.MbH; // a priori guess. @@ -693,7 +725,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy Span tmpVBuffer = dec.TmpVBuffer.Memory.Span; Span topU = tmpUBuffer; Span topV = tmpVBuffer; - int bpp = 3; + const int bpp = 3; int bufferStride = bpp * io.Width; int dstStartIdx = io.MbY * bufferStride; Span dst = buf[dstStartIdx..]; @@ -753,7 +785,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy return numLinesOut; } - private void DoTransform(uint bits, Span src, Span dst, Span scratch) + private static void DoTransform(uint bits, Span src, Span dst, Span scratch) { switch (bits >> 30) { @@ -769,7 +801,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } } - private void DoUVTransform(uint bits, Span src, Span dst, Span scratch) + private static void DoUVTransform(uint bits, Span src, Span dst, Span scratch) { // any non-zero coeff at all? if ((bits & 0xff) > 0) @@ -845,7 +877,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy // Parse DC short[] dc = new short[16]; int ctx = (int)(mb.NoneZeroDcCoeffs + leftMb.NoneZeroDcCoeffs); - int nz = this.GetCoeffs(br, bands[1], ctx, q.Y2Mat, 0, dc); + int nz = GetCoeffs(br, bands[1], ctx, q.Y2Mat, 0, dc); mb.NoneZeroDcCoeffs = leftMb.NoneZeroDcCoeffs = (uint)(nz > 0 ? 1 : 0); if (nz > 1) { @@ -876,7 +908,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy for (int x = 0; x < 4; x++) { int ctx = l + (tnz & 1); - int nz = this.GetCoeffs(br, acProba, ctx, q.Y1Mat, first, dst.AsSpan(dstOffset)); + int nz = GetCoeffs(br, acProba, ctx, q.Y1Mat, first, dst.AsSpan(dstOffset)); l = nz > first ? 1 : 0; tnz = (byte)((tnz >> 1) | (l << 7)); nzCoeffs = NzCodeBits(nzCoeffs, nz, dst[dstOffset] != 0 ? 1 : 0); @@ -903,7 +935,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy for (int x = 0; x < 2; x++) { int ctx = l + (tnz & 1); - int nz = this.GetCoeffs(br, bands[2], ctx, q.UvMat, 0, dst.AsSpan(dstOffset)); + int nz = GetCoeffs(br, bands[2], ctx, q.UvMat, 0, dst.AsSpan(dstOffset)); l = nz > 0 ? 1 : 0; tnz = (byte)((tnz >> 1) | (l << 3)); nzCoeffs = NzCodeBits(nzCoeffs, nz, dst[dstOffset] != 0 ? 1 : 0); @@ -929,7 +961,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy return (nonZeroY | nonZeroUv) == 0; } - private int GetCoeffs(Vp8BitReader br, Vp8BandProbas[] prob, int ctx, int[] dq, int n, Span coeffs) + private static int GetCoeffs(Vp8BitReader br, Vp8BandProbas[] prob, int ctx, int[] dq, int n, Span coeffs) { // Returns the position of the last non-zero coeff plus one. Vp8ProbaArray p = prob[n].Probabilities[ctx]; @@ -960,7 +992,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } else { - v = this.GetLargeValue(br, p.Probabilities); + v = GetLargeValue(br, p.Probabilities); p = prob[n + 1].Probabilities[2]; } @@ -971,7 +1003,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy return 16; } - private int GetLargeValue(Vp8BitReader br, byte[] p) + private static int GetLargeValue(Vp8BitReader br, byte[] p) { // See section 13 - 2: http://tools.ietf.org/html/rfc6386#section-13.2 int v; @@ -986,53 +1018,50 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy v = 3 + br.GetBit(p[5]); } } - else + else if (br.GetBit(p[6]) == 0) { - if (br.GetBit(p[6]) == 0) + if (br.GetBit(p[7]) == 0) { - if (br.GetBit(p[7]) == 0) - { - v = 5 + br.GetBit(159); - } - else - { - v = 7 + (2 * br.GetBit(165)); - v += br.GetBit(145); - } + v = 5 + br.GetBit(159); } else { - int bit1 = br.GetBit(p[8]); - int bit0 = br.GetBit(p[9 + bit1]); - int cat = (2 * bit1) + bit0; - v = 0; - byte[] tab = null; - switch (cat) - { - case 0: - tab = WebpConstants.Cat3; - break; - case 1: - tab = WebpConstants.Cat4; - break; - case 2: - tab = WebpConstants.Cat5; - break; - case 3: - tab = WebpConstants.Cat6; - break; - default: - WebpThrowHelper.ThrowImageFormatException("VP8 parsing error"); - break; - } - - for (int i = 0; i < tab.Length; i++) - { - v += v + br.GetBit(tab[i]); - } + v = 7 + (2 * br.GetBit(165)); + v += br.GetBit(145); + } + } + else + { + int bit1 = br.GetBit(p[8]); + int bit0 = br.GetBit(p[9 + bit1]); + int cat = (2 * bit1) + bit0; + v = 0; + byte[] tab = null; + switch (cat) + { + case 0: + tab = WebpConstants.Cat3; + break; + case 1: + tab = WebpConstants.Cat4; + break; + case 2: + tab = WebpConstants.Cat5; + break; + case 3: + tab = WebpConstants.Cat6; + break; + default: + WebpThrowHelper.ThrowImageFormatException("VP8 parsing error"); + break; + } - v += 3 + (8 << cat); + for (int i = 0; i < tab.Length; i++) + { + v += v + br.GetBit(tab[i]); } + + v += 3 + (8 << cat); } return v; @@ -1040,7 +1069,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy private Vp8SegmentHeader ParseSegmentHeader(Vp8Proba proba) { - var vp8SegmentHeader = new Vp8SegmentHeader + Vp8SegmentHeader vp8SegmentHeader = new() { UseSegment = this.bitReader.ReadBool() }; @@ -1055,15 +1084,13 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy for (int i = 0; i < vp8SegmentHeader.Quantizer.Length; i++) { hasValue = this.bitReader.ReadBool(); - byte quantizeValue = (byte)(hasValue ? this.bitReader.ReadSignedValue(7) : 0); - vp8SegmentHeader.Quantizer[i] = quantizeValue; + vp8SegmentHeader.Quantizer[i] = (byte)(hasValue ? this.bitReader.ReadSignedValue(7) : 0); } for (int i = 0; i < vp8SegmentHeader.FilterStrength.Length; i++) { hasValue = this.bitReader.ReadBool(); - byte filterStrengthValue = (byte)(hasValue ? this.bitReader.ReadSignedValue(6) : 0); - vp8SegmentHeader.FilterStrength[i] = filterStrengthValue; + vp8SegmentHeader.FilterStrength[i] = (byte)(hasValue ? this.bitReader.ReadSignedValue(6) : 0); } if (vp8SegmentHeader.UpdateMap) @@ -1188,10 +1215,8 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy decoder.DeQuantMatrices[i] = decoder.DeQuantMatrices[0]; continue; } - else - { - q = baseQ0; - } + + q = baseQ0; } Vp8QuantMatrix m = decoder.DeQuantMatrices[i]; @@ -1228,10 +1253,9 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy for (int p = 0; p < WebpConstants.NumProbas; ++p) { byte prob = WebpLookupTables.CoeffsUpdateProba[t, b, c, p]; - byte v = (byte)(this.bitReader.GetBit(prob) != 0 + proba.Bands[t, b].Probabilities[c].Probabilities[p] = (byte)(this.bitReader.GetBit(prob) != 0 ? this.bitReader.ReadValue(8) : WebpLookupTables.DefaultCoeffsProba[t, b, c, p]); - proba.Bands[t, b].Probabilities[c].Probabilities[p] = v; } } } @@ -1251,7 +1275,7 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy private static Vp8Io InitializeVp8Io(Vp8Decoder dec, Vp8PictureHeader pictureHeader) { - var io = default(Vp8Io); + Vp8Io io = default; io.Width = (int)pictureHeader.Width; io.Height = (int)pictureHeader.Height; io.UseScaling = false; @@ -1311,7 +1335,19 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy private static uint NzCodeBits(uint nzCoeffs, int nz, int dcNz) { nzCoeffs <<= 2; - nzCoeffs |= (uint)(nz > 3 ? 3 : nz > 1 ? 2 : dcNz); + if (nz > 3) + { + nzCoeffs |= 3; + } + else if (nz > 1) + { + nzCoeffs |= 2; + } + else + { + nzCoeffs |= (uint)dcNz; + } + return nzCoeffs; } @@ -1337,6 +1373,6 @@ namespace SixLabors.ImageSharp.Formats.Webp.Lossy } [MethodImpl(InliningOptions.ShortMethod)] - private static int Clip(int value, int max) => value < 0 ? 0 : value > max ? max : value; + private static int Clip(int value, int max) => Math.Clamp(value, 0, max); } } diff --git a/src/ImageSharp/Formats/Webp/WebpAnimationDecoder.cs b/src/ImageSharp/Formats/Webp/WebpAnimationDecoder.cs index abf501f4f7..2be64492ee 100644 --- a/src/ImageSharp/Formats/Webp/WebpAnimationDecoder.cs +++ b/src/ImageSharp/Formats/Webp/WebpAnimationDecoder.cs @@ -147,7 +147,7 @@ namespace SixLabors.ImageSharp.Formats.Webp } WebpImageInfo webpInfo = null; - var features = new WebpFeatures(); + WebpFeatures features = new(); switch (chunkType) { case WebpChunkType.Vp8: @@ -169,7 +169,7 @@ namespace SixLabors.ImageSharp.Formats.Webp { image = new Image(this.configuration, (int)width, (int)height, backgroundColor.ToPixel(), this.metadata); - this.SetFrameMetadata(image.Frames.RootFrame.Metadata, frameData.Duration); + SetFrameMetadata(image.Frames.RootFrame.Metadata, frameData.Duration); imageFrame = image.Frames.RootFrame; } @@ -177,7 +177,7 @@ namespace SixLabors.ImageSharp.Formats.Webp { currentFrame = image.Frames.AddFrame(previousFrame); // This clones the frame and adds it the collection. - this.SetFrameMetadata(currentFrame.Metadata, frameData.Duration); + SetFrameMetadata(currentFrame.Metadata, frameData.Duration); imageFrame = currentFrame; } @@ -186,7 +186,7 @@ namespace SixLabors.ImageSharp.Formats.Webp int frameY = (int)(frameData.Y * 2); int frameWidth = (int)frameData.Width; int frameHeight = (int)frameData.Height; - var regionRectangle = Rectangle.FromLTRB(frameX, frameY, frameX + frameWidth, frameY + frameHeight); + Rectangle regionRectangle = Rectangle.FromLTRB(frameX, frameY, frameX + frameWidth, frameY + frameHeight); if (frameData.DisposalMethod is AnimationDisposalMethod.Dispose) { @@ -194,7 +194,7 @@ namespace SixLabors.ImageSharp.Formats.Webp } using Buffer2D decodedImage = this.DecodeImageData(frameData, webpInfo); - this.DrawDecodedImageOnCanvas(decodedImage, imageFrame, frameX, frameY, frameWidth, frameHeight); + DrawDecodedImageOnCanvas(decodedImage, imageFrame, frameX, frameY, frameWidth, frameHeight); if (previousFrame != null && frameData.BlendingMethod is AnimationBlendingMethod.AlphaBlending) { @@ -213,7 +213,7 @@ namespace SixLabors.ImageSharp.Formats.Webp /// The metadata. /// The frame duration. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void SetFrameMetadata(ImageFrameMetadata meta, uint duration) + private static void SetFrameMetadata(ImageFrameMetadata meta, uint duration) { WebpFrameMetadata frameMetadata = meta.GetWebpMetadata(); frameMetadata.FrameDuration = duration; @@ -248,19 +248,19 @@ namespace SixLabors.ImageSharp.Formats.Webp private Buffer2D DecodeImageData(AnimationFrameData frameData, WebpImageInfo webpInfo) where TPixel : unmanaged, IPixel { - var decodedImage = new Image((int)frameData.Width, (int)frameData.Height); + Image decodedImage = new((int)frameData.Width, (int)frameData.Height); try { Buffer2D pixelBufferDecoded = decodedImage.Frames.RootFrame.PixelBuffer; if (webpInfo.IsLossless) { - var losslessDecoder = new WebpLosslessDecoder(webpInfo.Vp8LBitReader, this.memoryAllocator, this.configuration); + WebpLosslessDecoder losslessDecoder = new(webpInfo.Vp8LBitReader, this.memoryAllocator, this.configuration); losslessDecoder.Decode(pixelBufferDecoded, (int)webpInfo.Width, (int)webpInfo.Height); } else { - var lossyDecoder = new WebpLossyDecoder(webpInfo.Vp8BitReader, this.memoryAllocator, this.configuration); + WebpLossyDecoder lossyDecoder = new(webpInfo.Vp8BitReader, this.memoryAllocator, this.configuration); lossyDecoder.Decode(pixelBufferDecoded, (int)webpInfo.Width, (int)webpInfo.Height, webpInfo, this.alphaData); } @@ -278,7 +278,7 @@ namespace SixLabors.ImageSharp.Formats.Webp } /// - /// Draws the decoded image on canvas. The decoded image can be smaller the the canvas. + /// Draws the decoded image on canvas. The decoded image can be smaller the canvas. /// /// The type of the pixel. /// The decoded image. @@ -287,7 +287,7 @@ namespace SixLabors.ImageSharp.Formats.Webp /// The frame y coordinate. /// The width of the frame. /// The height of the frame. - private void DrawDecodedImageOnCanvas(Buffer2D decodedImage, ImageFrame imageFrame, int frameX, int frameY, int frameWidth, int frameHeight) + private static void DrawDecodedImageOnCanvas(Buffer2D decodedImage, ImageFrame imageFrame, int frameX, int frameY, int frameWidth, int frameHeight) where TPixel : unmanaged, IPixel { Buffer2D imageFramePixels = imageFrame.PixelBuffer; @@ -341,7 +341,7 @@ namespace SixLabors.ImageSharp.Formats.Webp return; } - var interest = Rectangle.Intersect(imageFrame.Bounds(), this.restoreArea.Value); + Rectangle interest = Rectangle.Intersect(imageFrame.Bounds(), this.restoreArea.Value); Buffer2DRegion pixelRegion = imageFrame.PixelBuffer.GetRegion(interest); TPixel backgroundPixel = backgroundColor.ToPixel(); pixelRegion.Fill(backgroundPixel); @@ -354,25 +354,25 @@ namespace SixLabors.ImageSharp.Formats.Webp /// Animation frame data. private AnimationFrameData ReadFrameHeader(BufferedReadStream stream) { - var data = new AnimationFrameData + AnimationFrameData data = new() { - DataSize = WebpChunkParsingUtils.ReadChunkSize(stream, this.buffer) - }; + DataSize = WebpChunkParsingUtils.ReadChunkSize(stream, this.buffer), - // 3 bytes for the X coordinate of the upper left corner of the frame. - data.X = WebpChunkParsingUtils.ReadUnsignedInt24Bit(stream, this.buffer); + // 3 bytes for the X coordinate of the upper left corner of the frame. + X = WebpChunkParsingUtils.ReadUnsignedInt24Bit(stream, this.buffer), - // 3 bytes for the Y coordinate of the upper left corner of the frame. - data.Y = WebpChunkParsingUtils.ReadUnsignedInt24Bit(stream, this.buffer); + // 3 bytes for the Y coordinate of the upper left corner of the frame. + Y = WebpChunkParsingUtils.ReadUnsignedInt24Bit(stream, this.buffer), - // Frame width Minus One. - data.Width = WebpChunkParsingUtils.ReadUnsignedInt24Bit(stream, this.buffer) + 1; + // Frame width Minus One. + Width = WebpChunkParsingUtils.ReadUnsignedInt24Bit(stream, this.buffer) + 1, - // Frame height Minus One. - data.Height = WebpChunkParsingUtils.ReadUnsignedInt24Bit(stream, this.buffer) + 1; + // Frame height Minus One. + Height = WebpChunkParsingUtils.ReadUnsignedInt24Bit(stream, this.buffer) + 1, - // Frame duration. - data.Duration = WebpChunkParsingUtils.ReadUnsignedInt24Bit(stream, this.buffer); + // Frame duration. + Duration = WebpChunkParsingUtils.ReadUnsignedInt24Bit(stream, this.buffer) + }; byte flags = (byte)stream.ReadByte(); data.DisposalMethod = (flags & 1) == 1 ? AnimationDisposalMethod.Dispose : AnimationDisposalMethod.DoNotDispose; diff --git a/src/ImageSharp/Formats/Webp/WebpImageFormatDetector.cs b/src/ImageSharp/Formats/Webp/WebpImageFormatDetector.cs index 9e672afb3e..cdb6e56627 100644 --- a/src/ImageSharp/Formats/Webp/WebpImageFormatDetector.cs +++ b/src/ImageSharp/Formats/Webp/WebpImageFormatDetector.cs @@ -14,22 +14,26 @@ namespace SixLabors.ImageSharp.Formats.Webp public int HeaderSize => 12; /// - public IImageFormat DetectFormat(ReadOnlySpan header) => this.IsSupportedFileFormat(header) ? WebpFormat.Instance : null; + public IImageFormat DetectFormat(ReadOnlySpan header) + => this.IsSupportedFileFormat(header) ? WebpFormat.Instance : null; - private bool IsSupportedFileFormat(ReadOnlySpan header) => header.Length >= this.HeaderSize && this.IsRiffContainer(header) && this.IsWebpFile(header); + private bool IsSupportedFileFormat(ReadOnlySpan header) + => header.Length >= this.HeaderSize && IsRiffContainer(header) && IsWebpFile(header); /// /// Checks, if the header starts with a valid RIFF FourCC. /// /// The header bytes. /// True, if its a valid RIFF FourCC. - private bool IsRiffContainer(ReadOnlySpan header) => header[..4].SequenceEqual(WebpConstants.RiffFourCc); + private static bool IsRiffContainer(ReadOnlySpan header) + => header[..4].SequenceEqual(WebpConstants.RiffFourCc); /// /// Checks if 'WEBP' is present in the header. /// /// The header bytes. /// True, if its a webp file. - private bool IsWebpFile(ReadOnlySpan header) => header.Slice(8, 4).SequenceEqual(WebpConstants.WebpHeader); + private static bool IsWebpFile(ReadOnlySpan header) + => header.Slice(8, 4).SequenceEqual(WebpConstants.WebpHeader); } } diff --git a/src/ImageSharp/Formats/Webp/WebpImageInfo.cs b/src/ImageSharp/Formats/Webp/WebpImageInfo.cs index 5b74de6803..3c9eea38c5 100644 --- a/src/ImageSharp/Formats/Webp/WebpImageInfo.cs +++ b/src/ImageSharp/Formats/Webp/WebpImageInfo.cs @@ -49,14 +49,14 @@ namespace SixLabors.ImageSharp.Formats.Webp public Vp8FrameHeader Vp8FrameHeader { get; set; } /// - /// Gets or sets the VP8L bitreader. Will be null, if its not a lossless image. + /// Gets or sets the VP8L bitreader. Will be , if its not a lossless image. /// - public Vp8LBitReader Vp8LBitReader { get; set; } = null; + public Vp8LBitReader Vp8LBitReader { get; set; } /// - /// Gets or sets the VP8 bitreader. Will be null, if its not a lossy image. + /// Gets or sets the VP8 bitreader. Will be , if its not a lossy image. /// - public Vp8BitReader Vp8BitReader { get; set; } = null; + public Vp8BitReader Vp8BitReader { get; set; } /// public void Dispose() diff --git a/src/ImageSharp/IO/BufferedReadStream.cs b/src/ImageSharp/IO/BufferedReadStream.cs index 572563ef3f..e6aeadea23 100644 --- a/src/ImageSharp/IO/BufferedReadStream.cs +++ b/src/ImageSharp/IO/BufferedReadStream.cs @@ -112,7 +112,7 @@ namespace SixLabors.ImageSharp.IO public override bool CanSeek { get; } = true; /// - public override bool CanWrite { get; } = false; + public override bool CanWrite { get; } /// /// Gets remaining byte count available to read. diff --git a/src/ImageSharp/IO/ChunkedMemoryStream.cs b/src/ImageSharp/IO/ChunkedMemoryStream.cs index 49e3d7f2fc..837af618ec 100644 --- a/src/ImageSharp/IO/ChunkedMemoryStream.cs +++ b/src/ImageSharp/IO/ChunkedMemoryStream.cs @@ -203,7 +203,7 @@ namespace SixLabors.ImageSharp.IO this.isDisposed = true; if (disposing) { - this.ReleaseMemoryChunks(this.memoryChunk); + ReleaseMemoryChunks(this.memoryChunk); } this.memoryChunk = null; @@ -530,7 +530,7 @@ namespace SixLabors.ImageSharp.IO }; } - private void ReleaseMemoryChunks(MemoryChunk chunk) + private static void ReleaseMemoryChunks(MemoryChunk chunk) { while (chunk != null) { diff --git a/src/ImageSharp/Image.FromStream.cs b/src/ImageSharp/Image.FromStream.cs index 5c73590aa1..4d1b172313 100644 --- a/src/ImageSharp/Image.FromStream.cs +++ b/src/ImageSharp/Image.FromStream.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.IO; using System.Text; using System.Threading; @@ -546,7 +547,7 @@ namespace SixLabors.ImageSharp } // We want to be able to load images from things like HttpContext.Request.Body - using var memoryStream = new ChunkedMemoryStream(configuration.MemoryAllocator); + using ChunkedMemoryStream memoryStream = new(configuration.MemoryAllocator); stream.CopyTo(memoryStream, configuration.StreamProcessingBufferSize); memoryStream.Position = 0; @@ -562,6 +563,7 @@ namespace SixLabors.ImageSharp /// The action to perform. /// The cancellation token. /// The . + /// Cannot read from the stream. internal static async Task WithSeekableStreamAsync( DecoderOptions options, Stream stream, @@ -577,19 +579,16 @@ namespace SixLabors.ImageSharp } Configuration configuration = options.Configuration; - if (stream.CanSeek) + if (stream.CanSeek && configuration.ReadOrigin == ReadOrigin.Begin) { - if (configuration.ReadOrigin == ReadOrigin.Begin) - { - stream.Position = 0; - } + stream.Position = 0; // NOTE: We are explicitly not executing the action against the stream here as we do in WithSeekableStream() because that // would incur synchronous IO reads which must be avoided in this asynchronous method. Instead, we will *always* run the // code below to copy the stream to an in-memory buffer before invoking the action. } - using var memoryStream = new ChunkedMemoryStream(configuration.MemoryAllocator); + using ChunkedMemoryStream memoryStream = new(configuration.MemoryAllocator); await stream.CopyToAsync(memoryStream, configuration.StreamProcessingBufferSize, cancellationToken).ConfigureAwait(false); memoryStream.Position = 0; @@ -599,12 +598,12 @@ namespace SixLabors.ImageSharp [DoesNotReturn] private static void ThrowNotLoaded(DecoderOptions options) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine("Image cannot be loaded. Available decoders:"); foreach (KeyValuePair val in options.Configuration.ImageFormatsManager.ImageDecoders) { - sb.AppendFormat(" - {0} : {1}{2}", val.Key.Name, val.Value.GetType().Name, Environment.NewLine); + sb.AppendFormat(CultureInfo.InvariantCulture, " - {0} : {1}{2}", val.Key.Name, val.Value.GetType().Name, Environment.NewLine); } throw new UnknownImageFormatException(sb.ToString()); diff --git a/src/ImageSharp/Image.WrapMemory.cs b/src/ImageSharp/Image.WrapMemory.cs index 6646e43c28..9e68d901a6 100644 --- a/src/ImageSharp/Image.WrapMemory.cs +++ b/src/ImageSharp/Image.WrapMemory.cs @@ -53,7 +53,7 @@ namespace SixLabors.ImageSharp Guard.NotNull(metadata, nameof(metadata)); Guard.IsTrue(pixelMemory.Length >= width * height, nameof(pixelMemory), "The length of the input memory is less than the specified image size"); - var memorySource = MemoryGroup.Wrap(pixelMemory); + MemoryGroup memorySource = MemoryGroup.Wrap(pixelMemory); return new Image(configuration, memorySource, width, height, metadata); } @@ -148,7 +148,7 @@ namespace SixLabors.ImageSharp Guard.NotNull(metadata, nameof(metadata)); Guard.IsTrue(pixelMemoryOwner.Memory.Length >= width * height, nameof(pixelMemoryOwner), "The length of the input memory is less than the specified image size"); - var memorySource = MemoryGroup.Wrap(pixelMemoryOwner); + MemoryGroup memorySource = MemoryGroup.Wrap(pixelMemoryOwner); return new Image(configuration, memorySource, width, height, metadata); } @@ -231,11 +231,11 @@ namespace SixLabors.ImageSharp Guard.NotNull(configuration, nameof(configuration)); Guard.NotNull(metadata, nameof(metadata)); - var memoryManager = new ByteMemoryManager(byteMemory); + ByteMemoryManager memoryManager = new(byteMemory); Guard.IsTrue(memoryManager.Memory.Length >= width * height, nameof(byteMemory), "The length of the input memory is less than the specified image size"); - var memorySource = MemoryGroup.Wrap(memoryManager.Memory); + MemoryGroup memorySource = MemoryGroup.Wrap(memoryManager.Memory); return new Image(configuration, memorySource, width, height, metadata); } @@ -329,11 +329,11 @@ namespace SixLabors.ImageSharp Guard.NotNull(configuration, nameof(configuration)); Guard.NotNull(metadata, nameof(metadata)); - var pixelMemoryOwner = new ByteMemoryOwner(byteMemoryOwner); + ByteMemoryOwner pixelMemoryOwner = new(byteMemoryOwner); Guard.IsTrue(pixelMemoryOwner.Memory.Length >= (long)width * height, nameof(pixelMemoryOwner), "The length of the input memory is less than the specified image size"); - var memorySource = MemoryGroup.Wrap(pixelMemoryOwner); + MemoryGroup memorySource = MemoryGroup.Wrap(pixelMemoryOwner); return new Image(configuration, memorySource, width, height, metadata); } @@ -422,9 +422,9 @@ namespace SixLabors.ImageSharp Guard.NotNull(configuration, nameof(configuration)); Guard.NotNull(metadata, nameof(metadata)); - var memoryManager = new UnmanagedMemoryManager(pointer, width * height); + UnmanagedMemoryManager memoryManager = new(pointer, width * height); - var memorySource = MemoryGroup.Wrap(memoryManager.Memory); + MemoryGroup memorySource = MemoryGroup.Wrap(memoryManager.Memory); return new Image(configuration, memorySource, width, height, metadata); } diff --git a/src/ImageSharp/ImageExtensions.cs b/src/ImageSharp/ImageExtensions.cs index 182047aff7..9427c8d616 100644 --- a/src/ImageSharp/ImageExtensions.cs +++ b/src/ImageSharp/ImageExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Text; using System.Threading; @@ -106,12 +107,12 @@ namespace SixLabors.ImageSharp if (encoder is null) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine("No encoder was found for the provided mime type. Registered encoders include:"); foreach (KeyValuePair val in source.GetConfiguration().ImageFormatsManager.ImageEncoders) { - sb.AppendFormat(" - {0} : {1}{2}", val.Key.Name, val.Value.GetType().Name, Environment.NewLine); + sb.AppendFormat(CultureInfo.InvariantCulture, " - {0} : {1}{2}", val.Key.Name, val.Value.GetType().Name, Environment.NewLine); } throw new NotSupportedException(sb.ToString()); @@ -150,12 +151,12 @@ namespace SixLabors.ImageSharp if (encoder is null) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine("No encoder was found for the provided mime type. Registered encoders include:"); foreach (KeyValuePair val in source.GetConfiguration().ImageFormatsManager.ImageEncoders) { - sb.AppendFormat(" - {0} : {1}{2}", val.Key.Name, val.Value.GetType().Name, Environment.NewLine); + sb.AppendFormat(CultureInfo.InvariantCulture, " - {0} : {1}{2}", val.Key.Name, val.Value.GetType().Name, Environment.NewLine); } throw new NotSupportedException(sb.ToString()); @@ -182,7 +183,7 @@ namespace SixLabors.ImageSharp { Guard.NotNull(format, nameof(format)); - using var stream = new MemoryStream(); + using MemoryStream stream = new(); source.Save(stream, format); // Always available. diff --git a/src/ImageSharp/ImageSharp.csproj.DotSettings b/src/ImageSharp/ImageSharp.csproj.DotSettings deleted file mode 100644 index 6896e069c2..0000000000 --- a/src/ImageSharp/ImageSharp.csproj.DotSettings +++ /dev/null @@ -1,15 +0,0 @@ - - True - True - True - True - True - True - True - True - True - True - True - True - True - True \ No newline at end of file diff --git a/src/ImageSharp/ImageSharp.netstandard1.1.v3.ncrunchproject b/src/ImageSharp/ImageSharp.netstandard1.1.v3.ncrunchproject deleted file mode 100644 index 319cd523ce..0000000000 --- a/src/ImageSharp/ImageSharp.netstandard1.1.v3.ncrunchproject +++ /dev/null @@ -1,5 +0,0 @@ - - - True - - \ No newline at end of file diff --git a/src/ImageSharp/Memory/Allocators/Internals/UnmanagedMemoryHandle.cs b/src/ImageSharp/Memory/Allocators/Internals/UnmanagedMemoryHandle.cs index 74a98ed1af..7933f3e13f 100644 --- a/src/ImageSharp/Memory/Allocators/Internals/UnmanagedMemoryHandle.cs +++ b/src/ImageSharp/Memory/Allocators/Internals/UnmanagedMemoryHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -24,7 +24,7 @@ namespace SixLabors.ImageSharp.Memory.Internals // A Monitor to wait/signal when we are low on memory. private static object lowMemoryMonitor; - public static readonly UnmanagedMemoryHandle NullHandle = default; + public static readonly UnmanagedMemoryHandle NullHandle; private IntPtr handle; private int lengthInBytes; @@ -80,24 +80,17 @@ namespace SixLabors.ImageSharp.Memory.Internals { handle = Marshal.AllocHGlobal(lengthInBytes); } - catch (OutOfMemoryException) + catch (OutOfMemoryException) when (counter < MaxAllocationAttempts) { // We are low on memory, but expect some memory to be freed soon. // Block the thread & retry to avoid OOM. - if (counter < MaxAllocationAttempts) - { - counter++; - Interlocked.Increment(ref totalOomRetries); - - Interlocked.CompareExchange(ref lowMemoryMonitor, new object(), null); - Monitor.Enter(lowMemoryMonitor); - Monitor.Wait(lowMemoryMonitor, millisecondsTimeout: 1); - Monitor.Exit(lowMemoryMonitor); - } - else - { - throw; - } + counter++; + Interlocked.Increment(ref totalOomRetries); + + Interlocked.CompareExchange(ref lowMemoryMonitor, new object(), null); + Monitor.Enter(lowMemoryMonitor); + Monitor.Wait(lowMemoryMonitor, millisecondsTimeout: 1); + Monitor.Exit(lowMemoryMonitor); } } diff --git a/src/ImageSharp/Metadata/Profiles/Exif/ExifReader.cs b/src/ImageSharp/Metadata/Profiles/Exif/ExifReader.cs index b2b1b28317..722f59316f 100644 --- a/src/ImageSharp/Metadata/Profiles/Exif/ExifReader.cs +++ b/src/ImageSharp/Metadata/Profiles/Exif/ExifReader.cs @@ -7,7 +7,9 @@ using System.Buffers.Binary; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; +using System.Globalization; using System.IO; +using System.Linq; using System.Runtime.CompilerServices; using System.Text; using SixLabors.ImageSharp.Memory; @@ -34,7 +36,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif /// public List ReadValues() { - var values = new List(); + List values = new(); // II == 0x4949 this.IsBigEndian = this.ReadUInt16() != 0x4949; @@ -64,11 +66,12 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif return; } - var values = new List(); + List values = new(); this.ReadValues(values, offset); - foreach (ExifValue value in values) + for (int i = 0; i < values.Count; i++) { + ExifValue value = (ExifValue)values[i]; if (value == ExifTag.JPEGInterchangeFormat) { this.ThumbnailOffset = ((ExifLong)value).Value; @@ -229,7 +232,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif int dataTypeSize = (int)ExifDataTypes.GetSize(dataType); int length = data.Length / dataTypeSize; - var result = new TDataType[length]; + TDataType[] result = new TDataType[length]; for (int i = 0; i < length; i++) { @@ -370,7 +373,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif return; } - var tag = (ExifTagValue)this.ReadUInt16(); + ExifTagValue tag = (ExifTagValue)this.ReadUInt16(); ExifDataType dataType = EnumUtils.Parse(this.ReadUInt16(), ExifDataType.Unknown); uint numberOfComponents = this.ReadUInt32(); @@ -426,7 +429,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif return; } - var tag = (ExifTagValue)this.ReadUInt16(); + ExifTagValue tag = (ExifTagValue)this.ReadUInt16(); ExifDataType dataType = EnumUtils.Parse(this.ReadUInt16(), ExifDataType.Unknown); ulong numberOfComponents = this.ReadUInt64(); @@ -511,7 +514,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif => (this.invalidTags ??= new List()).Add(tag); private void AddSubIfd(object val) - => (this.subIfds ??= new List()).Add(Convert.ToUInt64(val)); + => (this.subIfds ??= new List()).Add(Convert.ToUInt64(val, CultureInfo.InvariantCulture)); private void Seek(ulong pos) => this.data.Seek((long)pos, SeekOrigin.Begin); diff --git a/src/ImageSharp/Metadata/Profiles/Exif/ExifWriter.cs b/src/ImageSharp/Metadata/Profiles/Exif/ExifWriter.cs index ed22ff6476..1212e16ccc 100644 --- a/src/ImageSharp/Metadata/Profiles/Exif/ExifWriter.cs +++ b/src/ImageSharp/Metadata/Profiles/Exif/ExifWriter.cs @@ -49,9 +49,9 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif IExifValue exifOffset = GetOffsetValue(this.ifdValues, this.exifValues, ExifTag.SubIFDOffset); IExifValue gpsOffset = GetOffsetValue(this.ifdValues, this.gpsValues, ExifTag.GPSIFDOffset); - uint ifdLength = this.GetLength(this.ifdValues); - uint exifLength = this.GetLength(this.exifValues); - uint gpsLength = this.GetLength(this.gpsValues); + uint ifdLength = GetLength(this.ifdValues); + uint exifLength = GetLength(this.exifValues); + uint gpsLength = GetLength(this.gpsValues); uint length = ifdLength + exifLength + gpsLength; @@ -100,14 +100,14 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif private static unsafe int WriteSingle(float value, Span destination, int offset) { - BinaryPrimitives.WriteInt32LittleEndian(destination.Slice(offset, 4), *((int*)&value)); + BinaryPrimitives.WriteInt32LittleEndian(destination.Slice(offset, 4), *(int*)&value); return offset + 4; } private static unsafe int WriteDouble(double value, Span destination, int offset) { - BinaryPrimitives.WriteInt64LittleEndian(destination.Slice(offset, 8), *((long*)&value)); + BinaryPrimitives.WriteInt64LittleEndian(destination.Slice(offset, 8), *(long*)&value); return offset + 8; } @@ -195,7 +195,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif private List GetPartValues(ExifParts part) { - var result = new List(); + List result = new(); if (!EnumUtils.HasFlag(this.allowedParts, part)) { @@ -240,7 +240,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif return true; } - private uint GetLength(IList values) + private static uint GetLength(IList values) { if (values.Count == 0) { @@ -360,9 +360,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif } // next IFD offset - newOffset = WriteUInt32(0, destination, newOffset); - - return newOffset; + return WriteUInt32(0, destination, newOffset); } private static void WriteRational(Span destination, in Rational value) @@ -413,7 +411,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif WriteRational(destination.Slice(offset, 8), (Rational)value); return offset + 8; case ExifDataType.SignedByte: - destination[offset] = unchecked((byte)((sbyte)value)); + destination[offset] = unchecked((byte)(sbyte)value); return offset + 1; case ExifDataType.SignedLong: return WriteInt32((int)value, destination, offset); diff --git a/src/ImageSharp/Metadata/Profiles/Exif/Values/EncodedString.cs b/src/ImageSharp/Metadata/Profiles/Exif/Values/EncodedString.cs index 2209586abb..2af413cb95 100644 --- a/src/ImageSharp/Metadata/Profiles/Exif/Values/EncodedString.cs +++ b/src/ImageSharp/Metadata/Profiles/Exif/Values/EncodedString.cs @@ -79,6 +79,28 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Exif /// The to convert. public static explicit operator string(EncodedString encodedString) => encodedString.Text; + /// + /// Checks whether two structures are equal. + /// + /// The left hand operand. + /// The right hand operand. + /// + /// True if the parameter is equal to the parameter; + /// otherwise, false. + /// + public static bool operator ==(EncodedString left, EncodedString right) => left.Equals(right); + + /// + /// Checks whether two structures are not equal. + /// + /// The left hand operand. + /// The right hand operand. + /// + /// True if the parameter is not equal to the parameter; + /// otherwise, false. + /// + public static bool operator !=(EncodedString left, EncodedString right) => !(left == right); + /// public override bool Equals(object obj) => obj is EncodedString other && this.Equals(other); diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccCurveSegment.cs b/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccCurveSegment.cs index a4603a02a0..6fa985eb2c 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccCurveSegment.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccCurveSegment.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -15,9 +15,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// The signature of this segment protected IccCurveSegment(IccCurveSegmentSignature signature) - { - this.Signature = signature; - } + => this.Signature = signature; /// /// Gets the signature of this segment @@ -39,5 +37,11 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return this.Signature == other.Signature; } + + /// + public override bool Equals(object obj) => this.Equals(obj as IccCurveSegment); + + /// + public override int GetHashCode() => this.Signature.GetHashCode(); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccFormulaCurveElement.cs b/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccFormulaCurveElement.cs index a22c7dcde3..5ad61d4a04 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccFormulaCurveElement.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccFormulaCurveElement.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -85,9 +85,20 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } /// - public bool Equals(IccFormulaCurveElement other) - { - return this.Equals((IccCurveSegment)other); - } + public bool Equals(IccFormulaCurveElement other) => this.Equals((IccCurveSegment)other); + + /// + public override bool Equals(object obj) => this.Equals(obj as IccFormulaCurveElement); + + /// + public override int GetHashCode() + => HashCode.Combine( + this.Type, + this.Gamma, + this.A, + this.B, + this.C, + this.D, + this.E); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccOneDimensionalCurve.cs b/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccOneDimensionalCurve.cs index 773140ab2f..d84a18f902 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccOneDimensionalCurve.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccOneDimensionalCurve.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -53,5 +53,13 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return this.BreakPoints.AsSpan().SequenceEqual(other.BreakPoints) && this.Segments.AsSpan().SequenceEqual(other.Segments); } + + /// + public override bool Equals(object obj) + => this.Equals(obj as IccOneDimensionalCurve); + + /// + public override int GetHashCode() + => HashCode.Combine(this.BreakPoints, this.Segments); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccSampledCurveElement.cs b/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccSampledCurveElement.cs index 30b3dafa30..a305eea31d 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccSampledCurveElement.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Curves/IccSampledCurveElement.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -41,8 +41,14 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public bool Equals(IccSampledCurveElement other) - { - return this.Equals((IccCurveSegment)other); - } + => this.Equals((IccCurveSegment)other); + + /// + public override bool Equals(object obj) + => this.Equals(obj as IccSampledCurveElement); + + /// + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), this.CurveEntries); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntry.cs index f7c7d0a816..176c463353 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.TagDataEntry.cs @@ -230,7 +230,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc byte b = this.data[this.AddIndex(1)]; // last bit of 4th byte is either 0 = ASCII or 1 = binary - bool ascii = this.GetBit(b, 7); + bool ascii = GetBit(b, 7); int length = (int)size - 12; byte[] cdata = this.ReadBytes(length); diff --git a/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.cs b/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.cs index bd85cfbf47..35c8678274 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/DataReader/IccDataReader.cs @@ -25,9 +25,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// The data to read public IccDataReader(byte[] data) - { - this.data = data ?? throw new ArgumentNullException(nameof(data)); - } + => this.data = data ?? throw new ArgumentNullException(nameof(data)); /// /// Gets the length in bytes of the raw data @@ -39,9 +37,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// The new index position public void SetIndex(int index) - { - this.currentIndex = Numerics.Clamp(index, 0, this.data.Length); - } + => this.currentIndex = Numerics.Clamp(index, 0, this.data.Length); /// /// Returns the current without increment and adds the given increment @@ -59,9 +55,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// Calculates the 4 byte padding and adds it to the variable /// private void AddPadding() - { - this.currentIndex += this.CalcPadding(); - } + => this.currentIndex += this.CalcPadding(); /// /// Calculates the 4 byte padding @@ -79,9 +73,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// The value from where the bit will be extracted /// Position of the bit. Zero based index from left to right. /// The bit value at specified position - private bool GetBit(byte value, int position) - { - return ((value >> (7 - position)) & 1) == 1; - } + private static bool GetBit(byte value, int position) + => ((value >> (7 - position)) & 1) == 1; } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/DataWriter/IccDataWriter.TagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/DataWriter/IccDataWriter.TagDataEntry.cs index 411cdacece..8ff48bf134 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/DataWriter/IccDataWriter.TagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/DataWriter/IccDataWriter.TagDataEntry.cs @@ -34,116 +34,46 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc { int count = this.WriteTagDataEntryHeader(entry.Signature); - switch (entry.Signature) - { - case IccTypeSignature.Chromaticity: - count += this.WriteChromaticityTagDataEntry((IccChromaticityTagDataEntry)entry); - break; - case IccTypeSignature.ColorantOrder: - count += this.WriteColorantOrderTagDataEntry((IccColorantOrderTagDataEntry)entry); - break; - case IccTypeSignature.ColorantTable: - count += this.WriteColorantTableTagDataEntry((IccColorantTableTagDataEntry)entry); - break; - case IccTypeSignature.Curve: - count += this.WriteCurveTagDataEntry((IccCurveTagDataEntry)entry); - break; - case IccTypeSignature.Data: - count += this.WriteDataTagDataEntry((IccDataTagDataEntry)entry); - break; - case IccTypeSignature.DateTime: - count += this.WriteDateTimeTagDataEntry((IccDateTimeTagDataEntry)entry); - break; - case IccTypeSignature.Lut16: - count += this.WriteLut16TagDataEntry((IccLut16TagDataEntry)entry); - break; - case IccTypeSignature.Lut8: - count += this.WriteLut8TagDataEntry((IccLut8TagDataEntry)entry); - break; - case IccTypeSignature.LutAToB: - count += this.WriteLutAtoBTagDataEntry((IccLutAToBTagDataEntry)entry); - break; - case IccTypeSignature.LutBToA: - count += this.WriteLutBtoATagDataEntry((IccLutBToATagDataEntry)entry); - break; - case IccTypeSignature.Measurement: - count += this.WriteMeasurementTagDataEntry((IccMeasurementTagDataEntry)entry); - break; - case IccTypeSignature.MultiLocalizedUnicode: - count += this.WriteMultiLocalizedUnicodeTagDataEntry((IccMultiLocalizedUnicodeTagDataEntry)entry); - break; - case IccTypeSignature.MultiProcessElements: - count += this.WriteMultiProcessElementsTagDataEntry((IccMultiProcessElementsTagDataEntry)entry); - break; - case IccTypeSignature.NamedColor2: - count += this.WriteNamedColor2TagDataEntry((IccNamedColor2TagDataEntry)entry); - break; - case IccTypeSignature.ParametricCurve: - count += this.WriteParametricCurveTagDataEntry((IccParametricCurveTagDataEntry)entry); - break; - case IccTypeSignature.ProfileSequenceDesc: - count += this.WriteProfileSequenceDescTagDataEntry((IccProfileSequenceDescTagDataEntry)entry); - break; - case IccTypeSignature.ProfileSequenceIdentifier: - count += this.WriteProfileSequenceIdentifierTagDataEntry((IccProfileSequenceIdentifierTagDataEntry)entry); - break; - case IccTypeSignature.ResponseCurveSet16: - count += this.WriteResponseCurveSet16TagDataEntry((IccResponseCurveSet16TagDataEntry)entry); - break; - case IccTypeSignature.S15Fixed16Array: - count += this.WriteFix16ArrayTagDataEntry((IccFix16ArrayTagDataEntry)entry); - break; - case IccTypeSignature.Signature: - count += this.WriteSignatureTagDataEntry((IccSignatureTagDataEntry)entry); - break; - case IccTypeSignature.Text: - count += this.WriteTextTagDataEntry((IccTextTagDataEntry)entry); - break; - case IccTypeSignature.U16Fixed16Array: - count += this.WriteUFix16ArrayTagDataEntry((IccUFix16ArrayTagDataEntry)entry); - break; - case IccTypeSignature.UInt16Array: - count += this.WriteUInt16ArrayTagDataEntry((IccUInt16ArrayTagDataEntry)entry); - break; - case IccTypeSignature.UInt32Array: - count += this.WriteUInt32ArrayTagDataEntry((IccUInt32ArrayTagDataEntry)entry); - break; - case IccTypeSignature.UInt64Array: - count += this.WriteUInt64ArrayTagDataEntry((IccUInt64ArrayTagDataEntry)entry); - break; - case IccTypeSignature.UInt8Array: - count += this.WriteUInt8ArrayTagDataEntry((IccUInt8ArrayTagDataEntry)entry); - break; - case IccTypeSignature.ViewingConditions: - count += this.WriteViewingConditionsTagDataEntry((IccViewingConditionsTagDataEntry)entry); - break; - case IccTypeSignature.Xyz: - count += this.WriteXyzTagDataEntry((IccXyzTagDataEntry)entry); - break; + count += entry.Signature switch + { + IccTypeSignature.Chromaticity => this.WriteChromaticityTagDataEntry((IccChromaticityTagDataEntry)entry), + IccTypeSignature.ColorantOrder => this.WriteColorantOrderTagDataEntry((IccColorantOrderTagDataEntry)entry), + IccTypeSignature.ColorantTable => this.WriteColorantTableTagDataEntry((IccColorantTableTagDataEntry)entry), + IccTypeSignature.Curve => this.WriteCurveTagDataEntry((IccCurveTagDataEntry)entry), + IccTypeSignature.Data => this.WriteDataTagDataEntry((IccDataTagDataEntry)entry), + IccTypeSignature.DateTime => this.WriteDateTimeTagDataEntry((IccDateTimeTagDataEntry)entry), + IccTypeSignature.Lut16 => this.WriteLut16TagDataEntry((IccLut16TagDataEntry)entry), + IccTypeSignature.Lut8 => this.WriteLut8TagDataEntry((IccLut8TagDataEntry)entry), + IccTypeSignature.LutAToB => this.WriteLutAtoBTagDataEntry((IccLutAToBTagDataEntry)entry), + IccTypeSignature.LutBToA => this.WriteLutBtoATagDataEntry((IccLutBToATagDataEntry)entry), + IccTypeSignature.Measurement => this.WriteMeasurementTagDataEntry((IccMeasurementTagDataEntry)entry), + IccTypeSignature.MultiLocalizedUnicode => this.WriteMultiLocalizedUnicodeTagDataEntry((IccMultiLocalizedUnicodeTagDataEntry)entry), + IccTypeSignature.MultiProcessElements => this.WriteMultiProcessElementsTagDataEntry((IccMultiProcessElementsTagDataEntry)entry), + IccTypeSignature.NamedColor2 => this.WriteNamedColor2TagDataEntry((IccNamedColor2TagDataEntry)entry), + IccTypeSignature.ParametricCurve => this.WriteParametricCurveTagDataEntry((IccParametricCurveTagDataEntry)entry), + IccTypeSignature.ProfileSequenceDesc => this.WriteProfileSequenceDescTagDataEntry((IccProfileSequenceDescTagDataEntry)entry), + IccTypeSignature.ProfileSequenceIdentifier => this.WriteProfileSequenceIdentifierTagDataEntry((IccProfileSequenceIdentifierTagDataEntry)entry), + IccTypeSignature.ResponseCurveSet16 => this.WriteResponseCurveSet16TagDataEntry((IccResponseCurveSet16TagDataEntry)entry), + IccTypeSignature.S15Fixed16Array => this.WriteFix16ArrayTagDataEntry((IccFix16ArrayTagDataEntry)entry), + IccTypeSignature.Signature => this.WriteSignatureTagDataEntry((IccSignatureTagDataEntry)entry), + IccTypeSignature.Text => this.WriteTextTagDataEntry((IccTextTagDataEntry)entry), + IccTypeSignature.U16Fixed16Array => this.WriteUFix16ArrayTagDataEntry((IccUFix16ArrayTagDataEntry)entry), + IccTypeSignature.UInt16Array => this.WriteUInt16ArrayTagDataEntry((IccUInt16ArrayTagDataEntry)entry), + IccTypeSignature.UInt32Array => this.WriteUInt32ArrayTagDataEntry((IccUInt32ArrayTagDataEntry)entry), + IccTypeSignature.UInt64Array => this.WriteUInt64ArrayTagDataEntry((IccUInt64ArrayTagDataEntry)entry), + IccTypeSignature.UInt8Array => this.WriteUInt8ArrayTagDataEntry((IccUInt8ArrayTagDataEntry)entry), + IccTypeSignature.ViewingConditions => this.WriteViewingConditionsTagDataEntry((IccViewingConditionsTagDataEntry)entry), + IccTypeSignature.Xyz => this.WriteXyzTagDataEntry((IccXyzTagDataEntry)entry), // V2 Types: - case IccTypeSignature.TextDescription: - count += this.WriteTextDescriptionTagDataEntry((IccTextDescriptionTagDataEntry)entry); - break; - case IccTypeSignature.CrdInfo: - count += this.WriteCrdInfoTagDataEntry((IccCrdInfoTagDataEntry)entry); - break; - case IccTypeSignature.Screening: - count += this.WriteScreeningTagDataEntry((IccScreeningTagDataEntry)entry); - break; - case IccTypeSignature.UcrBg: - count += this.WriteUcrBgTagDataEntry((IccUcrBgTagDataEntry)entry); - break; + IccTypeSignature.TextDescription => this.WriteTextDescriptionTagDataEntry((IccTextDescriptionTagDataEntry)entry), + IccTypeSignature.CrdInfo => this.WriteCrdInfoTagDataEntry((IccCrdInfoTagDataEntry)entry), + IccTypeSignature.Screening => this.WriteScreeningTagDataEntry((IccScreeningTagDataEntry)entry), + IccTypeSignature.UcrBg => this.WriteUcrBgTagDataEntry((IccUcrBgTagDataEntry)entry), // Unsupported or unknown - case IccTypeSignature.DeviceSettings: - case IccTypeSignature.NamedColor: - case IccTypeSignature.Unknown: - default: - count += this.WriteUnknownTagDataEntry(entry as IccUnknownTagDataEntry); - break; - } - + _ => this.WriteUnknownTagDataEntry(entry as IccUnknownTagDataEntry), + }; return count; } @@ -153,10 +83,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// The signature of the entry /// The number of bytes written public int WriteTagDataEntryHeader(IccTypeSignature signature) - { - return this.WriteUInt32((uint)signature) - + this.WriteEmpty(4); - } + => this.WriteUInt32((uint)signature) + this.WriteEmpty(4); /// /// Writes a @@ -190,10 +117,8 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// The entry to write /// The number of bytes written public int WriteColorantOrderTagDataEntry(IccColorantOrderTagDataEntry value) - { - return this.WriteUInt32((uint)value.ColorantNumber.Length) - + this.WriteArray(value.ColorantNumber); - } + => this.WriteUInt32((uint)value.ColorantNumber.Length) + + this.WriteArray(value.ColorantNumber); /// /// Writes a @@ -255,11 +180,9 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// The entry to write /// The number of bytes written public int WriteDataTagDataEntry(IccDataTagDataEntry value) - { - return this.WriteEmpty(3) - + this.WriteByte((byte)(value.IsAscii ? 0x01 : 0x00)) - + this.WriteArray(value.Data); - } + => this.WriteEmpty(3) + + this.WriteByte((byte)(value.IsAscii ? 0x01 : 0x00)) + + this.WriteArray(value.Data); /// /// Writes a @@ -531,13 +454,11 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// The entry to write /// The number of bytes written public int WriteMeasurementTagDataEntry(IccMeasurementTagDataEntry value) - { - return this.WriteUInt32((uint)value.Observer) - + this.WriteXyzNumber(value.XyzBacking) - + this.WriteUInt32((uint)value.Geometry) - + this.WriteUFix16(value.Flare) - + this.WriteUInt32((uint)value.Illuminant); - } + => this.WriteUInt32((uint)value.Observer) + + this.WriteXyzNumber(value.XyzBacking) + + this.WriteUInt32((uint)value.Geometry) + + this.WriteUFix16(value.Flare) + + this.WriteUInt32((uint)value.Illuminant); /// /// Writes a @@ -560,8 +481,8 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc // TODO: Investigate cost of Linq GroupBy IGrouping[] texts = value.Texts.GroupBy(t => t.Text).ToArray(); - var offset = new uint[texts.Length]; - var lengths = new int[texts.Length]; + uint[] offset = new uint[texts.Length]; + int[] lengths = new int[texts.Length]; for (int i = 0; i < texts.Length; i++) { @@ -582,11 +503,11 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc count += this.WriteAsciiString("xx", 2, false); count += this.WriteAsciiString("\0\0", 2, false); } - else if (cultureName.Contains("-")) + else if (cultureName.Contains('-')) { string[] code = cultureName.Split('-'); - count += this.WriteAsciiString(code[0].ToLower(), 2, false); - count += this.WriteAsciiString(code[1].ToUpper(), 2, false); + count += this.WriteAsciiString(code[0].ToLower(localizedString.Culture), 2, false); + count += this.WriteAsciiString(code[1].ToUpper(localizedString.Culture), 2, false); } else { @@ -620,7 +541,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc long tpos = this.dataStream.Position; this.dataStream.Position += value.Data.Length * 8; - var posTable = new IccPositionNumber[value.Data.Length]; + IccPositionNumber[] posTable = new IccPositionNumber[value.Data.Length]; for (int i = 0; i < value.Data.Length; i++) { uint offset = (uint)(this.dataStream.Position - start); @@ -704,7 +625,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc // Jump over position table long tablePosition = this.dataStream.Position; this.dataStream.Position += length * 8; - var table = new IccPositionNumber[length]; + IccPositionNumber[] table = new IccPositionNumber[length]; for (int i = 0; i < length; i++) { @@ -746,7 +667,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc long tablePosition = this.dataStream.Position; this.dataStream.Position += value.Curves.Length * 4; - var offset = new uint[value.Curves.Length]; + uint[] offset = new uint[value.Curves.Length]; for (int i = 0; i < value.Curves.Length; i++) { @@ -844,11 +765,9 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// The entry to write /// The number of bytes written public int WriteViewingConditionsTagDataEntry(IccViewingConditionsTagDataEntry value) - { - return this.WriteXyzNumber(value.IlluminantXyz) - + this.WriteXyzNumber(value.SurroundXyz) - + this.WriteUInt32((uint)value.Illuminant); - } + => this.WriteXyzNumber(value.IlluminantXyz) + + this.WriteXyzNumber(value.SurroundXyz) + + this.WriteUInt32((uint)value.Illuminant); /// /// Writes a diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Enums/IccProfileFlag.cs b/src/ImageSharp/Metadata/Profiles/ICC/Enums/IccProfileFlag.cs index 7807ea4dfd..8a0c73882a 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Enums/IccProfileFlag.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Enums/IccProfileFlag.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -11,7 +11,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// the rest can be used for vendor specific values /// [Flags] - public enum IccProfileFlag : int + public enum IccProfileFlag { /// /// No flags (equivalent to NotEmbedded and Independent) @@ -24,7 +24,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc Embedded = 1 << 0, /// - /// Profile is embedded within another file + /// Profile is not embedded within another file /// NotEmbedded = 0, diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Enums/IccScreeningFlag.cs b/src/ImageSharp/Metadata/Profiles/ICC/Enums/IccScreeningFlag.cs index d76da63245..bcfc4f8c94 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Enums/IccScreeningFlag.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Enums/IccScreeningFlag.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -9,7 +9,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// Screening flags. Can be combined with a logical OR. /// [Flags] - internal enum IccScreeningFlag : int + internal enum IccScreeningFlag { /// /// No flags (equivalent to NotDefaultScreens and UnitLinesPerCm) diff --git a/src/ImageSharp/Metadata/Profiles/ICC/ICC.1-2022-05.pdf b/src/ImageSharp/Metadata/Profiles/ICC/ICC.1-2022-05.pdf new file mode 100644 index 0000000000..6c488c874b Binary files /dev/null and b/src/ImageSharp/Metadata/Profiles/ICC/ICC.1-2022-05.pdf differ diff --git a/src/ImageSharp/Metadata/Profiles/ICC/IccProfile.cs b/src/ImageSharp/Metadata/Profiles/ICC/IccProfile.cs index 2f1aa1952a..3752be1bac 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/IccProfile.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/IccProfile.cs @@ -91,7 +91,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } /// - public IccProfile DeepClone() => new IccProfile(this); + public IccProfile DeepClone() => new(this); /// /// Calculates the MD5 hash value of an ICC profile @@ -108,33 +108,33 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc const int profileIdPos = 84; // need to copy some values because they need to be zero for the hashing - var temp = new byte[24]; + byte[] temp = new byte[24]; Buffer.BlockCopy(data, profileFlagPos, temp, 0, 4); Buffer.BlockCopy(data, renderingIntentPos, temp, 4, 4); Buffer.BlockCopy(data, profileIdPos, temp, 8, 16); - using (var md5 = MD5.Create()) +#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms + using MD5 md5 = MD5.Create(); +#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms + try { - try - { - // Zero out some values - Array.Clear(data, profileFlagPos, 4); - Array.Clear(data, renderingIntentPos, 4); - Array.Clear(data, profileIdPos, 16); - - // Calculate hash - byte[] hash = md5.ComputeHash(data); - - // Read values from hash - var reader = new IccDataReader(hash); - return reader.ReadProfileId(); - } - finally - { - Buffer.BlockCopy(temp, 0, data, profileFlagPos, 4); - Buffer.BlockCopy(temp, 4, data, renderingIntentPos, 4); - Buffer.BlockCopy(temp, 8, data, profileIdPos, 16); - } + // Zero out some values + Array.Clear(data, profileFlagPos, 4); + Array.Clear(data, renderingIntentPos, 4); + Array.Clear(data, profileIdPos, 16); + + // Calculate hash + byte[] hash = md5.ComputeHash(data); + + // Read values from hash + IccDataReader reader = new(hash); + return reader.ReadProfileId(); + } + finally + { + Buffer.BlockCopy(temp, 0, data, profileFlagPos, 4); + Buffer.BlockCopy(temp, 4, data, renderingIntentPos, 4); + Buffer.BlockCopy(temp, 8, data, profileIdPos, 16); } } @@ -171,15 +171,13 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc { if (this.data != null) { - var copy = new byte[this.data.Length]; + byte[] copy = new byte[this.data.Length]; Buffer.BlockCopy(this.data, 0, copy, 0, copy.Length); return copy; } - else - { - var writer = new IccWriter(); - return writer.Write(this); - } + + IccWriter writer = new(); + return IccWriter.Write(this); } private void InitializeHeader() @@ -195,8 +193,8 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return; } - var reader = new IccReader(); - this.header = reader.ReadHeader(this.data); + IccReader reader = new(); + this.header = IccReader.ReadHeader(this.data); } private void InitializeEntries() @@ -212,8 +210,8 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return; } - var reader = new IccReader(); - this.entries = reader.ReadTagData(this.data); + IccReader reader = new(); + this.entries = IccReader.ReadTagData(this.data); } } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/IccReader.cs b/src/ImageSharp/Metadata/Profiles/ICC/IccReader.cs index 96a5e77a03..5e6e69fff6 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/IccReader.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/IccReader.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -16,14 +16,14 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// The raw ICC data /// The read ICC profile - public IccProfile Read(byte[] data) + public static IccProfile Read(byte[] data) { Guard.NotNull(data, nameof(data)); Guard.IsTrue(data.Length >= 128, nameof(data), "Data length must be at least 128 to be a valid ICC profile"); - var reader = new IccDataReader(data); - IccProfileHeader header = this.ReadHeader(reader); - IccTagDataEntry[] tagData = this.ReadTagData(reader); + IccDataReader reader = new(data); + IccProfileHeader header = ReadHeader(reader); + IccTagDataEntry[] tagData = ReadTagData(reader); return new IccProfile(header, tagData); } @@ -33,13 +33,13 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// The raw ICC data /// The read ICC profile header - public IccProfileHeader ReadHeader(byte[] data) + public static IccProfileHeader ReadHeader(byte[] data) { Guard.NotNull(data, nameof(data)); Guard.IsTrue(data.Length >= 128, nameof(data), "Data length must be at least 128 to be a valid profile header"); - var reader = new IccDataReader(data); - return this.ReadHeader(reader); + IccDataReader reader = new(data); + return ReadHeader(reader); } /// @@ -47,16 +47,16 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// The raw ICC data /// The read ICC profile tag data - public IccTagDataEntry[] ReadTagData(byte[] data) + public static IccTagDataEntry[] ReadTagData(byte[] data) { Guard.NotNull(data, nameof(data)); Guard.IsTrue(data.Length >= 128, nameof(data), "Data length must be at least 128 to be a valid ICC profile"); - var reader = new IccDataReader(data); - return this.ReadTagData(reader); + IccDataReader reader = new(data); + return ReadTagData(reader); } - private IccProfileHeader ReadHeader(IccDataReader reader) + private static IccProfileHeader ReadHeader(IccDataReader reader) { reader.SetIndex(0); @@ -82,11 +82,11 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc }; } - private IccTagDataEntry[] ReadTagData(IccDataReader reader) + private static IccTagDataEntry[] ReadTagData(IccDataReader reader) { - IccTagTableEntry[] tagTable = this.ReadTagTable(reader); - var entries = new List(tagTable.Length); - var store = new Dictionary(); + IccTagTableEntry[] tagTable = ReadTagTable(reader); + List entries = new(tagTable.Length); + Dictionary store = new(); foreach (IccTagTableEntry tag in tagTable) { @@ -117,7 +117,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return entries.ToArray(); } - private IccTagTableEntry[] ReadTagTable(IccDataReader reader) + private static IccTagTableEntry[] ReadTagTable(IccDataReader reader) { reader.SetIndex(128); // An ICC header is 128 bytes long @@ -130,7 +130,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return Array.Empty(); } - var table = new List((int)tagCount); + List table = new((int)tagCount); for (int i = 0; i < tagCount; i++) { uint tagSignature = reader.ReadUInt32(); diff --git a/src/ImageSharp/Metadata/Profiles/ICC/IccWriter.cs b/src/ImageSharp/Metadata/Profiles/ICC/IccWriter.cs index 2adfbbc7e5..4bf8b5eb93 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/IccWriter.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/IccWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System.Collections.Generic; @@ -16,20 +16,18 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// The ICC profile to write /// The ICC profile as a byte array - public byte[] Write(IccProfile profile) + public static byte[] Write(IccProfile profile) { Guard.NotNull(profile, nameof(profile)); - using (var writer = new IccDataWriter()) - { - IccTagTableEntry[] tagTable = this.WriteTagData(writer, profile.Entries); - this.WriteTagTable(writer, tagTable); - this.WriteHeader(writer, profile.Header); - return writer.GetData(); - } + using IccDataWriter writer = new(); + IccTagTableEntry[] tagTable = WriteTagData(writer, profile.Entries); + WriteTagTable(writer, tagTable); + WriteHeader(writer, profile.Header); + return writer.GetData(); } - private void WriteHeader(IccDataWriter writer, IccProfileHeader header) + private static void WriteHeader(IccDataWriter writer, IccProfileHeader header) { writer.SetIndex(0); @@ -54,7 +52,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc writer.WriteProfileId(id); } - private void WriteTagTable(IccDataWriter writer, IccTagTableEntry[] table) + private static void WriteTagTable(IccDataWriter writer, IccTagTableEntry[] table) { // 128 = size of ICC header writer.SetIndex(128); @@ -68,7 +66,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } } - private IccTagTableEntry[] WriteTagData(IccDataWriter writer, IccTagDataEntry[] entries) + private static IccTagTableEntry[] WriteTagData(IccDataWriter writer, IccTagDataEntry[] entries) { // TODO: Investigate cost of Linq GroupBy IEnumerable> grouped = entries.GroupBy(t => t); @@ -76,7 +74,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc // (Header size) + (entry count) + (nr of entries) * (size of table entry) writer.SetIndex(128 + 4 + (entries.Length * 12)); - var table = new List(); + List table = new(); foreach (IGrouping group in grouped) { writer.WriteTagDataEntry(group.Key, out IccTagTableEntry tableEntry); diff --git a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccBAcsProcessElement.cs b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccBAcsProcessElement.cs index d6882957ff..ef2e6eae0a 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccBAcsProcessElement.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccBAcsProcessElement.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -21,9 +21,12 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } /// - public bool Equals(IccBAcsProcessElement other) - { - return base.Equals(other); - } + public bool Equals(IccBAcsProcessElement other) => base.Equals(other); + + /// + public override bool Equals(object obj) => this.Equals(obj as IccBAcsProcessElement); + + /// + public override int GetHashCode() => base.GetHashCode(); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccClutProcessElement.cs b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccClutProcessElement.cs index e450362a5d..00183b6e85 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccClutProcessElement.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccClutProcessElement.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -16,9 +16,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// The color lookup table of this element public IccClutProcessElement(IccClut clutValue) : base(IccMultiProcessElementSignature.Clut, clutValue?.InputChannelCount ?? 1, clutValue?.OutputChannelCount ?? 1) - { - this.ClutValue = clutValue ?? throw new ArgumentNullException(nameof(clutValue)); - } + => this.ClutValue = clutValue ?? throw new ArgumentNullException(nameof(clutValue)); /// /// Gets the color lookup table of this element @@ -37,9 +35,12 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } /// - public bool Equals(IccClutProcessElement other) - { - return this.Equals((IccMultiProcessElement)other); - } + public bool Equals(IccClutProcessElement other) => this.Equals((IccMultiProcessElement)other); + + /// + public override bool Equals(object obj) => this.Equals(obj as IccClutProcessElement); + + /// + public override int GetHashCode() => base.GetHashCode(); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccCurveSetProcessElement.cs b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccCurveSetProcessElement.cs index 3ea707eec3..21b372ffa6 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccCurveSetProcessElement.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccCurveSetProcessElement.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -36,5 +36,11 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public bool Equals(IccCurveSetProcessElement other) => this.Equals((IccMultiProcessElement)other); + + /// + public override bool Equals(object obj) => this.Equals(obj as IccCurveSetProcessElement); + + /// + public override int GetHashCode() => base.GetHashCode(); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccEAcsProcessElement.cs b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccEAcsProcessElement.cs index 67f25b5ceb..5ce56bd11e 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccEAcsProcessElement.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccEAcsProcessElement.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -21,9 +21,11 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } /// - public bool Equals(IccEAcsProcessElement other) - { - return base.Equals(other); - } + public bool Equals(IccEAcsProcessElement other) => base.Equals(other); + + public override bool Equals(object obj) => this.Equals(obj as IccEAcsProcessElement); + + /// + public override int GetHashCode() => base.GetHashCode(); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccMatrixProcessElement.cs b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccMatrixProcessElement.cs index b7bde3f791..c448a71cd7 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccMatrixProcessElement.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccMatrixProcessElement.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -52,13 +52,17 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public bool Equals(IccMatrixProcessElement other) - { - return this.Equals((IccMultiProcessElement)other); - } + => this.Equals((IccMultiProcessElement)other); + + /// + public override bool Equals(object obj) + => this.Equals(obj as IccMatrixProcessElement); + + /// + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), this.MatrixIxO, this.MatrixOx1); private bool EqualsMatrix(IccMatrixProcessElement element) - { - return this.MatrixIxO.Equals(element.MatrixIxO); - } + => this.MatrixIxO.Equals(element.MatrixIxO); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccMultiProcessElement.cs b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccMultiProcessElement.cs index 3921212592..84d399459c 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccMultiProcessElement.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/MultiProcessElements/IccMultiProcessElement.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -58,5 +58,11 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc && this.InputChannelCount == other.InputChannelCount && this.OutputChannelCount == other.OutputChannelCount; } + + public override bool Equals(object obj) => this.Equals(obj as IccMultiProcessElement); + + /// + public override int GetHashCode() + => HashCode.Combine(this.Signature, this.InputChannelCount, this.OutputChannelCount); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccCrdInfoTagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccCrdInfoTagDataEntry.cs index 5d0bdabe7b..8b40dd7832 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccCrdInfoTagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccCrdInfoTagDataEntry.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -87,9 +87,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override bool Equals(IccTagDataEntry other) - { - return other is IccCrdInfoTagDataEntry entry && this.Equals(entry); - } + => other is IccCrdInfoTagDataEntry entry && this.Equals(entry); /// public bool Equals(IccCrdInfoTagDataEntry other) @@ -105,29 +103,25 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } return base.Equals(other) - && string.Equals(this.PostScriptProductName, other.PostScriptProductName) - && string.Equals(this.RenderingIntent0Crd, other.RenderingIntent0Crd) - && string.Equals(this.RenderingIntent1Crd, other.RenderingIntent1Crd) - && string.Equals(this.RenderingIntent2Crd, other.RenderingIntent2Crd) - && string.Equals(this.RenderingIntent3Crd, other.RenderingIntent3Crd); + && string.Equals(this.PostScriptProductName, other.PostScriptProductName, StringComparison.OrdinalIgnoreCase) + && string.Equals(this.RenderingIntent0Crd, other.RenderingIntent0Crd, StringComparison.OrdinalIgnoreCase) + && string.Equals(this.RenderingIntent1Crd, other.RenderingIntent1Crd, StringComparison.OrdinalIgnoreCase) + && string.Equals(this.RenderingIntent2Crd, other.RenderingIntent2Crd, StringComparison.OrdinalIgnoreCase) + && string.Equals(this.RenderingIntent3Crd, other.RenderingIntent3Crd, StringComparison.OrdinalIgnoreCase); } /// public override bool Equals(object obj) - { - return obj is IccCrdInfoTagDataEntry other && this.Equals(other); - } + => obj is IccCrdInfoTagDataEntry other && this.Equals(other); /// public override int GetHashCode() - { - return HashCode.Combine( + => HashCode.Combine( this.Signature, this.PostScriptProductName, this.RenderingIntent0Crd, this.RenderingIntent1Crd, this.RenderingIntent2Crd, this.RenderingIntent3Crd); - } } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccDataTagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccDataTagDataEntry.cs index 1a178b89a7..e5f817e958 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccDataTagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccDataTagDataEntry.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -40,7 +40,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc public IccDataTagDataEntry(byte[] data, bool isAscii, IccProfileTag tagSignature) : base(IccTypeSignature.Data, tagSignature) { - this.Data = data ?? throw new ArgumentException(nameof(data)); + this.Data = data ?? throw new ArgumentNullException(nameof(data)); this.IsAscii = isAscii; } @@ -62,9 +62,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override bool Equals(IccTagDataEntry other) - { - return other is IccDataTagDataEntry entry && this.Equals(entry); - } + => other is IccDataTagDataEntry entry && this.Equals(entry); /// public bool Equals(IccDataTagDataEntry other) @@ -84,17 +82,13 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override bool Equals(object obj) - { - return obj is IccDataTagDataEntry other && this.Equals(other); - } + => obj is IccDataTagDataEntry other && this.Equals(other); /// public override int GetHashCode() - { - return HashCode.Combine( + => HashCode.Combine( this.Signature, this.Data, this.IsAscii); - } } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLut8TagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLut8TagDataEntry.cs index 35542c1b4d..aa63c3b350 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLut8TagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLut8TagDataEntry.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -71,7 +71,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc bool is3By3 = matrix.GetLength(0) == 3 && matrix.GetLength(1) == 3; Guard.IsTrue(is3By3, nameof(matrix), "Matrix must have a size of three by three"); - this.Matrix = this.CreateMatrix(matrix); + this.Matrix = CreateMatrix(matrix); this.InputValues = inputValues ?? throw new ArgumentNullException(nameof(inputValues)); this.ClutValues = clutValues ?? throw new ArgumentNullException(nameof(clutValues)); this.OutputValues = outputValues ?? throw new ArgumentNullException(nameof(outputValues)); @@ -141,18 +141,15 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override int GetHashCode() - { - return HashCode.Combine( + => HashCode.Combine( this.Signature, this.Matrix, this.InputValues, this.ClutValues, this.OutputValues); - } - private Matrix4x4 CreateMatrix(float[,] matrix) - { - return new Matrix4x4( + private static Matrix4x4 CreateMatrix(float[,] matrix) + => new( matrix[0, 0], matrix[0, 1], matrix[0, 2], @@ -169,6 +166,5 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc 0, 0, 1); - } } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutAToBTagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutAToBTagDataEntry.cs index 21d46b0163..0c338dabd2 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutAToBTagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutAToBTagDataEntry.cs @@ -53,13 +53,13 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc IccProfileTag tagSignature) : base(IccTypeSignature.LutAToB, tagSignature) { - this.VerifyMatrix(matrix3x3, matrix3x1); + VerifyMatrix(matrix3x3, matrix3x1); this.VerifyCurve(curveA, nameof(curveA)); this.VerifyCurve(curveB, nameof(curveB)); this.VerifyCurve(curveM, nameof(curveM)); - this.Matrix3x3 = this.CreateMatrix3x3(matrix3x3); - this.Matrix3x1 = this.CreateMatrix3x1(matrix3x1); + this.Matrix3x3 = CreateMatrix3x3(matrix3x3); + this.Matrix3x1 = CreateMatrix3x1(matrix3x1); this.CurveA = curveA; this.CurveB = curveB; this.CurveM = curveM; @@ -212,29 +212,23 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } private bool IsAClutMMatrixB() - { - return this.CurveB != null - && this.Matrix3x3 != null - && this.Matrix3x1 != null - && this.CurveM != null - && this.ClutValues != null - && this.CurveA != null; - } + => this.CurveB != null + && this.Matrix3x3 != null + && this.Matrix3x1 != null + && this.CurveM != null + && this.ClutValues != null + && this.CurveA != null; private bool IsMMatrixB() - { - return this.CurveB != null - && this.Matrix3x3 != null - && this.Matrix3x1 != null - && this.CurveM != null; - } + => this.CurveB != null + && this.Matrix3x3 != null + && this.Matrix3x1 != null + && this.CurveM != null; private bool IsAClutB() - { - return this.CurveB != null - && this.ClutValues != null - && this.CurveA != null; - } + => this.CurveB != null + && this.ClutValues != null + && this.CurveA != null; private bool IsB() => this.CurveB != null; @@ -242,12 +236,12 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc { if (curves != null) { - bool isNotCurve = curves.Any(t => !(t is IccParametricCurveTagDataEntry) && !(t is IccCurveTagDataEntry)); + bool isNotCurve = curves.Any(t => t is not IccParametricCurveTagDataEntry and not IccCurveTagDataEntry); Guard.IsFalse(isNotCurve, nameof(name), $"{nameof(name)} must be of type {nameof(IccParametricCurveTagDataEntry)} or {nameof(IccCurveTagDataEntry)}"); } } - private void VerifyMatrix(float[,] matrix3x3, float[] matrix3x1) + private static void VerifyMatrix(float[,] matrix3x3, float[] matrix3x1) { if (matrix3x1 != null) { @@ -261,7 +255,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } } - private Vector3? CreateMatrix3x1(float[] matrix) + private static Vector3? CreateMatrix3x1(float[] matrix) { if (matrix is null) { @@ -271,7 +265,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return new Vector3(matrix[0], matrix[1], matrix[2]); } - private Matrix4x4? CreateMatrix3x3(float[,] matrix) + private static Matrix4x4? CreateMatrix3x3(float[,] matrix) { if (matrix is null) { diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutBToATagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutBToATagDataEntry.cs index 89b0101800..2c4487bcab 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutBToATagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccLutBToATagDataEntry.cs @@ -53,13 +53,13 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc IccProfileTag tagSignature) : base(IccTypeSignature.LutBToA, tagSignature) { - this.VerifyMatrix(matrix3x3, matrix3x1); + VerifyMatrix(matrix3x3, matrix3x1); this.VerifyCurve(curveA, nameof(curveA)); this.VerifyCurve(curveB, nameof(curveB)); this.VerifyCurve(curveM, nameof(curveM)); - this.Matrix3x3 = this.CreateMatrix3x3(matrix3x3); - this.Matrix3x1 = this.CreateMatrix3x1(matrix3x1); + this.Matrix3x3 = CreateMatrix3x3(matrix3x3); + this.Matrix3x1 = CreateMatrix3x1(matrix3x1); this.CurveA = curveA; this.CurveB = curveB; this.CurveM = curveM; @@ -167,9 +167,9 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc && this.Matrix3x3.Equals(other.Matrix3x3) && this.Matrix3x1.Equals(other.Matrix3x1) && this.ClutValues.Equals(other.ClutValues) - && this.EqualsCurve(this.CurveB, other.CurveB) - && this.EqualsCurve(this.CurveM, other.CurveM) - && this.EqualsCurve(this.CurveA, other.CurveA); + && EqualsCurve(this.CurveB, other.CurveB) + && EqualsCurve(this.CurveM, other.CurveM) + && EqualsCurve(this.CurveA, other.CurveA); } /// @@ -192,7 +192,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return hashCode.ToHashCode(); } - private bool EqualsCurve(IccTagDataEntry[] thisCurves, IccTagDataEntry[] entryCurves) + private static bool EqualsCurve(IccTagDataEntry[] thisCurves, IccTagDataEntry[] entryCurves) { bool thisNull = thisCurves is null; bool entryNull = entryCurves is null; @@ -211,29 +211,13 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } private bool IsBMatrixMClutA() - { - return this.CurveB != null - && this.Matrix3x3 != null - && this.Matrix3x1 != null - && this.CurveM != null - && this.ClutValues != null - && this.CurveA != null; - } + => this.CurveB != null && this.Matrix3x3 != null && this.Matrix3x1 != null && this.CurveM != null && this.ClutValues != null && this.CurveA != null; private bool IsBMatrixM() - { - return this.CurveB != null - && this.Matrix3x3 != null - && this.Matrix3x1 != null - && this.CurveM != null; - } + => this.CurveB != null && this.Matrix3x3 != null && this.Matrix3x1 != null && this.CurveM != null; private bool IsBClutA() - { - return this.CurveB != null - && this.ClutValues != null - && this.CurveA != null; - } + => this.CurveB != null && this.ClutValues != null && this.CurveA != null; private bool IsB() => this.CurveB != null; @@ -241,12 +225,12 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc { if (curves != null) { - bool isNotCurve = curves.Any(t => !(t is IccParametricCurveTagDataEntry) && !(t is IccCurveTagDataEntry)); + bool isNotCurve = curves.Any(t => t is not IccParametricCurveTagDataEntry and not IccCurveTagDataEntry); Guard.IsFalse(isNotCurve, nameof(name), $"{nameof(name)} must be of type {nameof(IccParametricCurveTagDataEntry)} or {nameof(IccCurveTagDataEntry)}"); } } - private void VerifyMatrix(float[,] matrix3x3, float[] matrix3x1) + private static void VerifyMatrix(float[,] matrix3x3, float[] matrix3x1) { if (matrix3x1 != null) { @@ -260,7 +244,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } } - private Vector3? CreateMatrix3x1(float[] matrix) + private static Vector3? CreateMatrix3x1(float[] matrix) { if (matrix is null) { @@ -270,7 +254,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return new Vector3(matrix[0], matrix[1], matrix[2]); } - private Matrix4x4? CreateMatrix3x3(float[,] matrix) + private static Matrix4x4? CreateMatrix3x3(float[,] matrix) { if (matrix is null) { diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccNamedColor2TagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccNamedColor2TagDataEntry.cs index c2c959d296..8541d287d8 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccNamedColor2TagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccNamedColor2TagDataEntry.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -121,9 +121,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override bool Equals(IccTagDataEntry other) - { - return other is IccNamedColor2TagDataEntry entry && this.Equals(entry); - } + => other is IccNamedColor2TagDataEntry entry && this.Equals(entry); /// public bool Equals(IccNamedColor2TagDataEntry other) @@ -140,28 +138,24 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return base.Equals(other) && this.CoordinateCount == other.CoordinateCount - && string.Equals(this.Prefix, other.Prefix) - && string.Equals(this.Suffix, other.Suffix) + && string.Equals(this.Prefix, other.Prefix, StringComparison.OrdinalIgnoreCase) + && string.Equals(this.Suffix, other.Suffix, StringComparison.OrdinalIgnoreCase) && this.VendorFlags == other.VendorFlags && this.Colors.AsSpan().SequenceEqual(other.Colors); } /// public override bool Equals(object obj) - { - return obj is IccNamedColor2TagDataEntry other && this.Equals(other); - } + => obj is IccNamedColor2TagDataEntry other && this.Equals(other); /// public override int GetHashCode() - { - return HashCode.Combine( + => HashCode.Combine( this.Signature, this.CoordinateCount, this.Prefix, this.Suffix, this.VendorFlags, this.Colors); - } } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccSignatureTagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccSignatureTagDataEntry.cs index 148450de60..2924a5dc6a 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccSignatureTagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccSignatureTagDataEntry.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -27,9 +27,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// Tag Signature public IccSignatureTagDataEntry(string signatureData, IccProfileTag tagSignature) : base(IccTypeSignature.Signature, tagSignature) - { - this.SignatureData = signatureData ?? throw new ArgumentNullException(nameof(signatureData)); - } + => this.SignatureData = signatureData ?? throw new ArgumentNullException(nameof(signatureData)); /// /// Gets the signature data @@ -38,9 +36,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override bool Equals(IccTagDataEntry other) - { - return other is IccSignatureTagDataEntry entry && this.Equals(entry); - } + => other is IccSignatureTagDataEntry entry && this.Equals(entry); /// public bool Equals(IccSignatureTagDataEntry other) @@ -55,14 +51,13 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return true; } - return base.Equals(other) && string.Equals(this.SignatureData, other.SignatureData); + return base.Equals(other) + && string.Equals(this.SignatureData, other.SignatureData, StringComparison.OrdinalIgnoreCase); } /// public override bool Equals(object obj) - { - return obj is IccSignatureTagDataEntry other && this.Equals(other); - } + => obj is IccSignatureTagDataEntry other && this.Equals(other); /// public override int GetHashCode() => HashCode.Combine(this.Signature, this.SignatureData); diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccTextDescriptionTagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccTextDescriptionTagDataEntry.cs index 1d9da5398e..6fb2aca203 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccTextDescriptionTagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccTextDescriptionTagDataEntry.cs @@ -104,7 +104,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return new IccMultiLocalizedUnicodeTagDataEntry(new[] { localString }, textEntry.TagSignature); - CultureInfo GetCulture(uint value) + static CultureInfo GetCulture(uint value) { if (value == 0) { @@ -122,7 +122,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc && p3 >= 0x41 && p3 <= 0x5A && p4 >= 0x41 && p4 <= 0x5A) { - var culture = new string(new[] { (char)p1, (char)p2, '-', (char)p3, (char)p4 }); + string culture = new(new[] { (char)p1, (char)p2, '-', (char)p3, (char)p4 }); return new CultureInfo(culture); } @@ -132,9 +132,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override bool Equals(IccTagDataEntry other) - { - return other is IccTextDescriptionTagDataEntry entry && this.Equals(entry); - } + => other is IccTextDescriptionTagDataEntry entry && this.Equals(entry); /// public bool Equals(IccTextDescriptionTagDataEntry other) @@ -150,29 +148,25 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc } return base.Equals(other) - && string.Equals(this.Ascii, other.Ascii) - && string.Equals(this.Unicode, other.Unicode) - && string.Equals(this.ScriptCode, other.ScriptCode) + && string.Equals(this.Ascii, other.Ascii, StringComparison.OrdinalIgnoreCase) + && string.Equals(this.Unicode, other.Unicode, StringComparison.OrdinalIgnoreCase) + && string.Equals(this.ScriptCode, other.ScriptCode, StringComparison.OrdinalIgnoreCase) && this.UnicodeLanguageCode == other.UnicodeLanguageCode && this.ScriptCodeCode == other.ScriptCodeCode; } /// public override bool Equals(object obj) - { - return obj is IccTextDescriptionTagDataEntry other && this.Equals(other); - } + => obj is IccTextDescriptionTagDataEntry other && this.Equals(other); /// public override int GetHashCode() - { - return HashCode.Combine( + => HashCode.Combine( this.Signature, this.Ascii, this.Unicode, this.ScriptCode, this.UnicodeLanguageCode, this.ScriptCodeCode); - } } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccTextTagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccTextTagDataEntry.cs index 4af43a1a8b..9463f665a8 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccTextTagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccTextTagDataEntry.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -26,9 +26,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// Tag Signature public IccTextTagDataEntry(string text, IccProfileTag tagSignature) : base(IccTypeSignature.Text, tagSignature) - { - this.Text = text ?? throw new ArgumentNullException(nameof(text)); - } + => this.Text = text ?? throw new ArgumentNullException(nameof(text)); /// /// Gets the Text @@ -37,9 +35,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override bool Equals(IccTagDataEntry other) - { - return other is IccTextTagDataEntry entry && this.Equals(entry); - } + => other is IccTextTagDataEntry entry && this.Equals(entry); /// public bool Equals(IccTextTagDataEntry other) @@ -54,14 +50,12 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return true; } - return base.Equals(other) && string.Equals(this.Text, other.Text); + return base.Equals(other) && string.Equals(this.Text, other.Text, StringComparison.OrdinalIgnoreCase); } /// public override bool Equals(object obj) - { - return obj is IccTextTagDataEntry other && this.Equals(other); - } + => obj is IccTextTagDataEntry other && this.Equals(other); /// public override int GetHashCode() => HashCode.Combine(this.Signature, this.Text); diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccUcrBgTagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccUcrBgTagDataEntry.cs index e48c9d3b3a..d806ca2a56 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccUcrBgTagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccUcrBgTagDataEntry.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -54,9 +54,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override bool Equals(IccTagDataEntry other) - { - return other is IccUcrBgTagDataEntry entry && this.Equals(entry); - } + => other is IccUcrBgTagDataEntry entry && this.Equals(entry); /// public bool Equals(IccUcrBgTagDataEntry other) @@ -74,23 +72,19 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return base.Equals(other) && this.UcrCurve.AsSpan().SequenceEqual(other.UcrCurve) && this.BgCurve.AsSpan().SequenceEqual(other.BgCurve) - && string.Equals(this.Description, other.Description); + && string.Equals(this.Description, other.Description, StringComparison.OrdinalIgnoreCase); } /// public override bool Equals(object obj) - { - return obj is IccUcrBgTagDataEntry other && this.Equals(other); - } + => obj is IccUcrBgTagDataEntry other && this.Equals(other); /// public override int GetHashCode() - { - return HashCode.Combine( + => HashCode.Combine( this.Signature, this.UcrCurve, this.BgCurve, this.Description); - } } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccXyzTagDataEntry.cs b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccXyzTagDataEntry.cs index 319ea8fde5..8a30802406 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccXyzTagDataEntry.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/TagDataEntries/IccXyzTagDataEntry.cs @@ -1,9 +1,8 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; using System.Numerics; -using System.Runtime.CompilerServices; namespace SixLabors.ImageSharp.Metadata.Profiles.Icc { @@ -28,9 +27,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// Tag Signature public IccXyzTagDataEntry(Vector3[] data, IccProfileTag tagSignature) : base(IccTypeSignature.Xyz, tagSignature) - { - this.Data = data ?? throw new ArgumentNullException(nameof(data)); - } + => this.Data = data ?? throw new ArgumentNullException(nameof(data)); /// /// Gets the XYZ numbers. @@ -50,8 +47,13 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public bool Equals(IccXyzTagDataEntry other) - { - return this.Equals((IccTagDataEntry)other); - } + => this.Equals((IccTagDataEntry)other); + + /// + public override bool Equals(object obj) + => this.Equals(obj as IccXyzTagDataEntry); + + public override int GetHashCode() + => HashCode.Combine(base.GetHashCode(), this.Data); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Various/IccLocalizedString.cs b/src/ImageSharp/Metadata/Profiles/ICC/Various/IccLocalizedString.cs index 20ca0248ab..63f97d45c8 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Various/IccLocalizedString.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Various/IccLocalizedString.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -50,5 +50,11 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override string ToString() => $"{this.Culture.Name}: {this.Text}"; + + public override bool Equals(object obj) + => obj is IccLocalizedString iccLocalizedString && this.Equals(iccLocalizedString); + + public override int GetHashCode() + => HashCode.Combine(this.Culture, this.Text); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Various/IccLut.cs b/src/ImageSharp/Metadata/Profiles/ICC/Various/IccLut.cs index dfe186d7d0..b5709db4d7 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Various/IccLut.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Various/IccLut.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -15,9 +15,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// The LUT values public IccLut(float[] values) - { - this.Values = values ?? throw new ArgumentNullException(nameof(values)); - } + => this.Values = values ?? throw new ArgumentNullException(nameof(values)); /// /// Initializes a new instance of the struct. @@ -68,5 +66,13 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc return this.Values.AsSpan().SequenceEqual(other.Values); } + + /// + public override bool Equals(object obj) + => obj is IccLut iccLut && this.Equals(iccLut); + + /// + public override int GetHashCode() + => this.Values.GetHashCode(); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Various/IccNamedColor.cs b/src/ImageSharp/Metadata/Profiles/ICC/Various/IccNamedColor.cs index a0e767a7c9..8010f78bc0 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Various/IccNamedColor.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Various/IccNamedColor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -71,20 +71,16 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public bool Equals(IccNamedColor other) - { - return this.Name.Equals(other.Name) - && this.PcsCoordinates.AsSpan().SequenceEqual(other.PcsCoordinates) - && this.DeviceCoordinates.AsSpan().SequenceEqual(other.DeviceCoordinates); - } + => this.Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) + && this.PcsCoordinates.AsSpan().SequenceEqual(other.PcsCoordinates) + && this.DeviceCoordinates.AsSpan().SequenceEqual(other.DeviceCoordinates); /// public override int GetHashCode() - { - return HashCode.Combine( + => HashCode.Combine( this.Name, this.PcsCoordinates, this.DeviceCoordinates); - } /// public override string ToString() => this.Name; diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Various/IccProfileId.cs b/src/ImageSharp/Metadata/Profiles/ICC/Various/IccProfileId.cs index 6633d2a687..b4e6e573b3 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Various/IccProfileId.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Various/IccProfileId.cs @@ -1,7 +1,8 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; +using System.Globalization; namespace SixLabors.ImageSharp.Metadata.Profiles.Icc { @@ -13,7 +14,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// A profile ID with all values set to zero /// - public static readonly IccProfileId Zero = default; + public static readonly IccProfileId Zero; /// /// Initializes a new instance of the struct. @@ -67,10 +68,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// True if the parameter is equal to the parameter; otherwise, false. /// - public static bool operator ==(IccProfileId left, IccProfileId right) - { - return left.Equals(right); - } + public static bool operator ==(IccProfileId left, IccProfileId right) => left.Equals(right); /// /// Compares two objects for equality. @@ -80,10 +78,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// /// True if the parameter is not equal to the parameter; otherwise, false. /// - public static bool operator !=(IccProfileId left, IccProfileId right) - { - return !left.Equals(right); - } + public static bool operator !=(IccProfileId left, IccProfileId right) => !left.Equals(right); /// public override bool Equals(object obj) => obj is IccProfileId other && this.Equals(other); @@ -97,17 +92,15 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override int GetHashCode() - { - return HashCode.Combine( + => HashCode.Combine( this.Part1, this.Part2, this.Part3, this.Part4); - } /// public override string ToString() => $"{ToHex(this.Part1)}-{ToHex(this.Part2)}-{ToHex(this.Part3)}-{ToHex(this.Part4)}"; - private static string ToHex(uint value) => value.ToString("X").PadLeft(8, '0'); + private static string ToHex(uint value) => value.ToString("X", CultureInfo.InvariantCulture).PadLeft(8, '0'); } } diff --git a/src/ImageSharp/Metadata/Profiles/ICC/Various/IccVersion.cs b/src/ImageSharp/Metadata/Profiles/ICC/Various/IccVersion.cs index f8f2b653a6..4b8cb91f7e 100644 --- a/src/ImageSharp/Metadata/Profiles/ICC/Various/IccVersion.cs +++ b/src/ImageSharp/Metadata/Profiles/ICC/Various/IccVersion.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -38,6 +38,28 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public int Patch { get; } + /// + /// Returns a value indicating whether the two values are equal. + /// + /// The first value. + /// The second value. + /// if the two value are equal; otherwise, . + public static bool operator ==(IccVersion left, IccVersion right) + => left.Equals(right); + + /// + /// Returns a value indicating whether the two values are not equal. + /// + /// The first value. + /// The second value. + /// if the two value are not equal; otherwise, . + public static bool operator !=(IccVersion left, IccVersion right) + => !(left == right); + + /// + public override bool Equals(object obj) + => obj is IccVersion iccVersion && this.Equals(iccVersion); + /// public bool Equals(IccVersion other) => this.Major == other.Major && @@ -46,8 +68,10 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Icc /// public override string ToString() - { - return string.Join(".", this.Major, this.Minor, this.Patch); - } + => string.Join(".", this.Major, this.Minor, this.Patch); + + /// + public override int GetHashCode() + => HashCode.Combine(this.Major, this.Minor, this.Patch); } } diff --git a/src/ImageSharp/Metadata/Profiles/IPTC/IptcProfile.cs b/src/ImageSharp/Metadata/Profiles/IPTC/IptcProfile.cs index ec3eed2650..bc94e95552 100644 --- a/src/ImageSharp/Metadata/Profiles/IPTC/IptcProfile.cs +++ b/src/ImageSharp/Metadata/Profiles/IPTC/IptcProfile.cs @@ -5,6 +5,7 @@ using System; using System.Buffers.Binary; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.Text; using SixLabors.ImageSharp.Metadata.Profiles.IPTC; @@ -102,7 +103,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Iptc /// The values found with the specified tag. public List GetValues(IptcTag tag) { - var iptcValues = new List(); + List iptcValues = new(); foreach (IptcValue iptcValue in this.Values) { if (iptcValue.Tag == tag) @@ -149,7 +150,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Iptc bool removed = false; for (int i = this.values.Count - 1; i >= 0; i--) { - if (this.values[i].Tag == tag && this.values[i].Value.Equals(value)) + if (this.values[i].Tag == tag && this.values[i].Value.Equals(value, StringComparison.OrdinalIgnoreCase)) { this.values.RemoveAt(i); removed = true; @@ -226,16 +227,17 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Iptc /// /// The tag of the iptc value. /// The datetime. + /// Iptc tag is not a time or date type. public void SetDateTimeValue(IptcTag tag, DateTimeOffset dateTimeOffset) { if (!tag.IsDate() && !tag.IsTime()) { - throw new ArgumentException("iptc tag is not a time or date type"); + throw new ArgumentException("Iptc tag is not a time or date type."); } string formattedDate = tag.IsDate() - ? dateTimeOffset.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture) - : dateTimeOffset.ToString("HHmmsszzzz", System.Globalization.CultureInfo.InvariantCulture) + ? dateTimeOffset.ToString("yyyyMMdd", CultureInfo.InvariantCulture) + : dateTimeOffset.ToString("HHmmsszzzz", CultureInfo.InvariantCulture) .Replace(":", string.Empty); this.SetValue(tag, Encoding.UTF8, formattedDate); @@ -329,7 +331,7 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Iptc bool isValidTagMarker = this.Data[offset++] == IptcTagMarkerByte; byte recordNumber = this.Data[offset++]; bool isValidRecordNumber = recordNumber is >= 1 and <= 9; - var tag = (IptcTag)this.Data[offset++]; + IptcTag tag = (IptcTag)this.Data[offset++]; bool isValidEntry = isValidTagMarker && isValidRecordNumber; bool isApplicationRecord = recordNumber == (byte)IptcRecordNumber.Application; diff --git a/src/ImageSharp/Metadata/Profiles/XMP/XmpProfile.cs b/src/ImageSharp/Metadata/Profiles/XMP/XmpProfile.cs index 06595b9911..095beb24af 100644 --- a/src/ImageSharp/Metadata/Profiles/XMP/XmpProfile.cs +++ b/src/ImageSharp/Metadata/Profiles/XMP/XmpProfile.cs @@ -67,15 +67,15 @@ namespace SixLabors.ImageSharp.Metadata.Profiles.Xmp } } - using var stream = new MemoryStream(byteArray, 0, count); - using var reader = new StreamReader(stream, Encoding.UTF8); + using MemoryStream stream = new(byteArray, 0, count); + using StreamReader reader = new(stream, Encoding.UTF8); return XDocument.Load(reader); } /// /// Convert the content of this into a byte array. /// - /// The + /// The public byte[] ToByteArray() { byte[] result = new byte[this.Data.Length]; diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/HalfSingle.cs b/src/ImageSharp/PixelFormats/PixelImplementations/HalfSingle.cs index a415f41cc5..84354a5c28 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/HalfSingle.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/HalfSingle.cs @@ -18,8 +18,8 @@ namespace SixLabors.ImageSharp.PixelFormats /// /// Initializes a new instance of the struct. /// - /// The single component. - public HalfSingle(float single) => this.PackedValue = HalfTypeHelper.Pack(single); + /// The single component value. + public HalfSingle(float value) => this.PackedValue = HalfTypeHelper.Pack(value); /// public ushort PackedValue { get; set; } diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs b/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs index 55dd80af10..d15a46d698 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/Rgba32.cs @@ -240,6 +240,7 @@ namespace SixLabors.ImageSharp.PixelFormats /// /// The . /// + /// Hexadecimal string is not in the correct format. [MethodImpl(InliningOptions.ShortMethod)] public static Rgba32 ParseHex(string hex) { @@ -432,7 +433,7 @@ namespace SixLabors.ImageSharp.PixelFormats public readonly string ToHex() { uint hexOrder = (uint)((this.A << 0) | (this.B << 8) | (this.G << 16) | (this.R << 24)); - return hexOrder.ToString("X8"); + return hexOrder.ToString("X8", CultureInfo.InvariantCulture); } /// diff --git a/src/ImageSharp/PixelFormats/PixelImplementations/RgbaVector.cs b/src/ImageSharp/PixelFormats/PixelImplementations/RgbaVector.cs index 93037fcbce..7973ee3dc9 100644 --- a/src/ImageSharp/PixelFormats/PixelImplementations/RgbaVector.cs +++ b/src/ImageSharp/PixelFormats/PixelImplementations/RgbaVector.cs @@ -2,6 +2,7 @@ // Licensed under the Six Labors Split License. using System; +using System.Globalization; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -188,7 +189,7 @@ namespace SixLabors.ImageSharp.PixelFormats Vector4 vector = this.ToVector4() * Max; vector += Half; uint hexOrder = (uint)((byte)vector.W | ((byte)vector.Z << 8) | ((byte)vector.Y << 16) | ((byte)vector.X << 24)); - return hexOrder.ToString("X8"); + return hexOrder.ToString("X8", CultureInfo.InvariantCulture); } /// diff --git a/src/ImageSharp/PixelFormats/PixelOperations{TPixel}.cs b/src/ImageSharp/PixelFormats/PixelOperations{TPixel}.cs index 9d2a2f1b2d..0662ffb71a 100644 --- a/src/ImageSharp/PixelFormats/PixelOperations{TPixel}.cs +++ b/src/ImageSharp/PixelFormats/PixelOperations{TPixel}.cs @@ -20,11 +20,14 @@ namespace SixLabors.ImageSharp.PixelFormats where TPixel : unmanaged, IPixel { private static readonly Lazy LazyInfo = new(() => PixelTypeInfo.Create(), true); + private static readonly Lazy> LazyInstance = new(() => default(TPixel).CreatePixelOperations(), true); /// /// Gets the global instance for the pixel type /// - public static PixelOperations Instance { get; } = default(TPixel).CreatePixelOperations(); +#pragma warning disable CA1000 // Do not declare static members on generic types + public static PixelOperations Instance => LazyInstance.Value; +#pragma warning restore CA1000 // Do not declare static members on generic types /// /// Gets the pixel type info for the given . diff --git a/src/ImageSharp/Primitives/DenseMatrix{T}.cs b/src/ImageSharp/Primitives/DenseMatrix{T}.cs index 471e4f6b22..7eee4a1b08 100644 --- a/src/ImageSharp/Primitives/DenseMatrix{T}.cs +++ b/src/ImageSharp/Primitives/DenseMatrix{T}.cs @@ -16,31 +16,6 @@ namespace SixLabors.ImageSharp public readonly struct DenseMatrix : IEquatable> where T : struct, IEquatable { - /// - /// The 1D representation of the dense matrix. - /// - public readonly T[] Data; - - /// - /// Gets the number of columns in the dense matrix. - /// - public readonly int Columns; - - /// - /// Gets the number of rows in the dense matrix. - /// - public readonly int Rows; - - /// - /// Gets the size of the dense matrix. - /// - public readonly Size Size; - - /// - /// Gets the number of items in the array. - /// - public readonly int Count; - /// /// Initializes a new instance of the struct. /// @@ -96,10 +71,35 @@ namespace SixLabors.ImageSharp } } + /// + /// Gets the 1D representation of the dense matrix. + /// + public readonly T[] Data { get; } + + /// + /// Gets the number of columns in the dense matrix. + /// + public readonly int Columns { get; } + + /// + /// Gets the number of rows in the dense matrix. + /// + public readonly int Rows { get; } + + /// + /// Gets the size of the dense matrix. + /// + public readonly Size Size { get; } + + /// + /// Gets the number of items in the array. + /// + public readonly int Count { get; } + /// /// Gets a span wrapping the . /// - public Span Span => new Span(this.Data); + public Span Span => new(this.Data); /// /// Gets or sets the item at the specified position. @@ -125,7 +125,7 @@ namespace SixLabors.ImageSharp /// The representation on the source data. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator DenseMatrix(T[,] data) => new DenseMatrix(data); + public static implicit operator DenseMatrix(T[,] data) => new(data); /// /// Performs an implicit conversion from a to a . @@ -139,7 +139,7 @@ namespace SixLabors.ImageSharp public static implicit operator T[,](in DenseMatrix data) #pragma warning restore SA1008 // Opening parenthesis should be spaced correctly { - var result = new T[data.Rows, data.Columns]; + T[,] result = new T[data.Rows, data.Columns]; for (int y = 0; y < data.Rows; y++) { @@ -178,7 +178,7 @@ namespace SixLabors.ImageSharp [MethodImpl(MethodImplOptions.AggressiveInlining)] public DenseMatrix Transpose() { - var result = new DenseMatrix(this.Rows, this.Columns); + DenseMatrix result = new DenseMatrix(this.Rows, this.Columns); for (int y = 0; y < this.Rows; y++) { diff --git a/src/ImageSharp/Primitives/LongRational.cs b/src/ImageSharp/Primitives/LongRational.cs index a181084aa1..062036a57f 100644 --- a/src/ImageSharp/Primitives/LongRational.cs +++ b/src/ImageSharp/Primitives/LongRational.cs @@ -1,4 +1,4 @@ -// Copyright (c) Six Labors. +// Copyright (c) Six Labors. // Licensed under the Six Labors Split License. using System; @@ -66,23 +66,21 @@ namespace SixLabors.ImageSharp /// public bool IsZero => this.Denominator == 1 && this.Numerator == 0; + /// + public override bool Equals(object obj) + => obj is LongRational longRational && this.Equals(longRational); + /// public bool Equals(LongRational other) - { - return this.Numerator == other.Numerator && this.Denominator == other.Denominator; - } + => this.Numerator == other.Numerator && this.Denominator == other.Denominator; /// public override int GetHashCode() - { - return ((this.Numerator * 397) ^ this.Denominator).GetHashCode(); - } + => HashCode.Combine(this.Numerator, this.Denominator); /// public override string ToString() - { - return this.ToString(CultureInfo.InvariantCulture); - } + => this.ToString(CultureInfo.InvariantCulture); /// /// Converts the numeric value of this instance to its equivalent string representation using @@ -119,10 +117,11 @@ namespace SixLabors.ImageSharp return this.Numerator.ToString(provider); } - var sb = new StringBuilder(); - sb.Append(this.Numerator.ToString(provider)); - sb.Append('/'); - sb.Append(this.Denominator.ToString(provider)); + StringBuilder sb = new(); + sb.Append(this.Numerator.ToString(provider)) + .Append('/') + .Append(this.Denominator.ToString(provider)); + return sb.ToString(); } diff --git a/src/ImageSharp/Primitives/Point.cs b/src/ImageSharp/Primitives/Point.cs index 89db9befbb..356595cb4d 100644 --- a/src/ImageSharp/Primitives/Point.cs +++ b/src/ImageSharp/Primitives/Point.cs @@ -21,7 +21,7 @@ namespace SixLabors.ImageSharp /// /// Represents a that has X and Y values set to zero. /// - public static readonly Point Empty = default; + public static readonly Point Empty; /// /// Initializes a new instance of the struct. @@ -77,28 +77,28 @@ namespace SixLabors.ImageSharp /// /// The point. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator PointF(Point point) => new PointF(point.X, point.Y); + public static implicit operator PointF(Point point) => new(point.X, point.Y); /// /// Creates a with the coordinates of the specified . /// /// The point. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator Vector2(Point point) => new Vector2(point.X, point.Y); + public static implicit operator Vector2(Point point) => new(point.X, point.Y); /// /// Creates a with the coordinates of the specified . /// /// The point. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static explicit operator Size(Point point) => new Size(point.X, point.Y); + public static explicit operator Size(Point point) => new(point.X, point.Y); /// /// Negates the given point by multiplying all values by -1. /// /// The source point. /// The negated point. - public static Point operator -(Point value) => new Point(-value.X, -value.Y); + public static Point operator -(Point value) => new(-value.X, -value.Y); /// /// Translates a by a given . @@ -143,7 +143,7 @@ namespace SixLabors.ImageSharp /// Divisor of type . /// Result of type . public static Point operator /(Point left, int right) - => new Point(left.X / right, left.Y / right); + => new(left.X / right, left.Y / right); /// /// Compares two objects for equality. @@ -174,7 +174,7 @@ namespace SixLabors.ImageSharp /// The size on the right hand of the operand. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Point Add(Point point, Size size) => new Point(unchecked(point.X + size.Width), unchecked(point.Y + size.Height)); + public static Point Add(Point point, Size size) => new(unchecked(point.X + size.Width), unchecked(point.Y + size.Height)); /// /// Translates a by the negative of a given value. @@ -183,7 +183,7 @@ namespace SixLabors.ImageSharp /// The value on the right hand of the operand. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Point Multiply(Point point, int value) => new Point(unchecked(point.X * value), unchecked(point.Y * value)); + public static Point Multiply(Point point, int value) => new(unchecked(point.X * value), unchecked(point.Y * value)); /// /// Translates a by the negative of a given . @@ -192,7 +192,7 @@ namespace SixLabors.ImageSharp /// The size on the right hand of the operand. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Point Subtract(Point point, Size size) => new Point(unchecked(point.X - size.Width), unchecked(point.Y - size.Height)); + public static Point Subtract(Point point, Size size) => new(unchecked(point.X - size.Width), unchecked(point.Y - size.Height)); /// /// Converts a to a by performing a ceiling operation on all the coordinates. @@ -200,7 +200,7 @@ namespace SixLabors.ImageSharp /// The point. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Point Ceiling(PointF point) => new Point(unchecked((int)MathF.Ceiling(point.X)), unchecked((int)MathF.Ceiling(point.Y))); + public static Point Ceiling(PointF point) => new(unchecked((int)MathF.Ceiling(point.X)), unchecked((int)MathF.Ceiling(point.Y))); /// /// Converts a to a by performing a round operation on all the coordinates. @@ -208,7 +208,7 @@ namespace SixLabors.ImageSharp /// The point. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Point Round(PointF point) => new Point(unchecked((int)MathF.Round(point.X)), unchecked((int)MathF.Round(point.Y))); + public static Point Round(PointF point) => new(unchecked((int)MathF.Round(point.X)), unchecked((int)MathF.Round(point.Y))); /// /// Converts a to a by performing a round operation on all the coordinates. @@ -216,7 +216,7 @@ namespace SixLabors.ImageSharp /// The vector. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Point Round(Vector2 vector) => new Point(unchecked((int)MathF.Round(vector.X)), unchecked((int)MathF.Round(vector.Y))); + public static Point Round(Vector2 vector) => new(unchecked((int)MathF.Round(vector.X)), unchecked((int)MathF.Round(vector.Y))); /// /// Converts a to a by performing a truncate operation on all the coordinates. @@ -224,7 +224,7 @@ namespace SixLabors.ImageSharp /// The point. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Point Truncate(PointF point) => new Point(unchecked((int)point.X), unchecked((int)point.Y)); + public static Point Truncate(PointF point) => new(unchecked((int)point.X), unchecked((int)point.Y)); /// /// Transforms a point by a specified 3x2 matrix. diff --git a/src/ImageSharp/Primitives/PointF.cs b/src/ImageSharp/Primitives/PointF.cs index 9817f04f3e..d701f3d541 100644 --- a/src/ImageSharp/Primitives/PointF.cs +++ b/src/ImageSharp/Primitives/PointF.cs @@ -21,7 +21,7 @@ namespace SixLabors.ImageSharp /// /// Represents a that has X and Y values set to zero. /// - public static readonly PointF Empty = default; + public static readonly PointF Empty; /// /// Initializes a new instance of the struct. @@ -69,7 +69,7 @@ namespace SixLabors.ImageSharp /// The . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator PointF(Vector2 vector) => new PointF(vector.X, vector.Y); + public static implicit operator PointF(Vector2 vector) => new(vector.X, vector.Y); /// /// Creates a with the coordinates of the specified . @@ -79,7 +79,7 @@ namespace SixLabors.ImageSharp /// The . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator Vector2(PointF point) => new Vector2(point.X, point.Y); + public static implicit operator Vector2(PointF point) => new(point.X, point.Y); /// /// Creates a with the coordinates of the specified by truncating each of the coordinates. @@ -96,7 +96,7 @@ namespace SixLabors.ImageSharp /// /// The source point. /// The negated point. - public static PointF operator -(PointF value) => new PointF(-value.X, -value.Y); + public static PointF operator -(PointF value) => new(-value.X, -value.Y); /// /// Translates a by a given . @@ -161,7 +161,7 @@ namespace SixLabors.ImageSharp /// Divisor of type . /// Result of type . public static PointF operator /(PointF left, float right) - => new PointF(left.X / right, left.Y / right); + => new(left.X / right, left.Y / right); /// /// Compares two objects for equality. @@ -200,7 +200,7 @@ namespace SixLabors.ImageSharp /// The size on the right hand of the operand. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static PointF Add(PointF point, SizeF size) => new PointF(point.X + size.Width, point.Y + size.Height); + public static PointF Add(PointF point, SizeF size) => new(point.X + size.Width, point.Y + size.Height); /// /// Translates a by the given . @@ -209,7 +209,7 @@ namespace SixLabors.ImageSharp /// The point on the right hand of the operand. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static PointF Add(PointF point, PointF pointb) => new PointF(point.X + pointb.X, point.Y + pointb.Y); + public static PointF Add(PointF point, PointF pointb) => new(point.X + pointb.X, point.Y + pointb.Y); /// /// Translates a by the negative of a given . @@ -218,7 +218,7 @@ namespace SixLabors.ImageSharp /// The size on the right hand of the operand. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static PointF Subtract(PointF point, SizeF size) => new PointF(point.X - size.Width, point.Y - size.Height); + public static PointF Subtract(PointF point, SizeF size) => new(point.X - size.Width, point.Y - size.Height); /// /// Translates a by the negative of a given . @@ -227,7 +227,7 @@ namespace SixLabors.ImageSharp /// The point on the right hand of the operand. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static PointF Subtract(PointF point, PointF pointb) => new PointF(point.X - pointb.X, point.Y - pointb.Y); + public static PointF Subtract(PointF point, PointF pointb) => new(point.X - pointb.X, point.Y - pointb.Y); /// /// Translates a by the multiplying the X and Y by the given value. @@ -236,7 +236,7 @@ namespace SixLabors.ImageSharp /// The value on the right hand of the operand. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static PointF Multiply(PointF point, float right) => new PointF(point.X * right, point.Y * right); + public static PointF Multiply(PointF point, float right) => new(point.X * right, point.Y * right); /// /// Transforms a point by a specified 3x2 matrix. @@ -284,7 +284,7 @@ namespace SixLabors.ImageSharp public override string ToString() => $"PointF [ X={this.X}, Y={this.Y} ]"; /// - public override bool Equals(object obj) => obj is PointF && this.Equals((PointF)obj); + public override bool Equals(object obj) => obj is PointF pointF && this.Equals(pointF); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/ImageSharp/Primitives/Rectangle.cs b/src/ImageSharp/Primitives/Rectangle.cs index 4c70e0dd9a..b21aae1fe0 100644 --- a/src/ImageSharp/Primitives/Rectangle.cs +++ b/src/ImageSharp/Primitives/Rectangle.cs @@ -20,7 +20,7 @@ namespace SixLabors.ImageSharp /// /// Represents a that has X, Y, Width, and Height values set to zero. /// - public static readonly Rectangle Empty = default; + public static readonly Rectangle Empty; /// /// Initializes a new instance of the struct. diff --git a/src/ImageSharp/Primitives/RectangleF.cs b/src/ImageSharp/Primitives/RectangleF.cs index aa6f4fc236..9719d2b7e3 100644 --- a/src/ImageSharp/Primitives/RectangleF.cs +++ b/src/ImageSharp/Primitives/RectangleF.cs @@ -20,7 +20,7 @@ namespace SixLabors.ImageSharp /// /// Represents a that has X, Y, Width, and Height values set to zero. /// - public static readonly RectangleF Empty = default; + public static readonly RectangleF Empty; /// /// Initializes a new instance of the struct. @@ -81,7 +81,7 @@ namespace SixLabors.ImageSharp public PointF Location { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => new PointF(this.X, this.Y); + get => new(this.X, this.Y); [MethodImpl(MethodImplOptions.AggressiveInlining)] set @@ -98,7 +98,7 @@ namespace SixLabors.ImageSharp public SizeF Size { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => new SizeF(this.Width, this.Height); + get => new(this.Width, this.Height); [MethodImpl(MethodImplOptions.AggressiveInlining)] set @@ -181,7 +181,7 @@ namespace SixLabors.ImageSharp [MethodImpl(MethodImplOptions.AggressiveInlining)] // ReSharper disable once InconsistentNaming - public static RectangleF FromLTRB(float left, float top, float right, float bottom) => new RectangleF(left, top, right - left, bottom - top); + public static RectangleF FromLTRB(float left, float top, float right, float bottom) => new(left, top, right - left, bottom - top); /// /// Returns the center point of the given . @@ -189,7 +189,7 @@ namespace SixLabors.ImageSharp /// The rectangle. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static PointF Center(RectangleF rectangle) => new PointF(rectangle.Left + (rectangle.Width / 2), rectangle.Top + (rectangle.Height / 2)); + public static PointF Center(RectangleF rectangle) => new(rectangle.Left + (rectangle.Width / 2), rectangle.Top + (rectangle.Height / 2)); /// /// Creates a rectangle that represents the intersection between and @@ -372,15 +372,11 @@ namespace SixLabors.ImageSharp /// public override int GetHashCode() - { - return HashCode.Combine(this.X, this.Y, this.Width, this.Height); - } + => HashCode.Combine(this.X, this.Y, this.Width, this.Height); /// public override string ToString() - { - return $"RectangleF [ X={this.X}, Y={this.Y}, Width={this.Width}, Height={this.Height} ]"; - } + => $"RectangleF [ X={this.X}, Y={this.Y}, Width={this.Width}, Height={this.Height} ]"; /// public override bool Equals(object obj) => obj is RectangleF other && this.Equals(other); diff --git a/src/ImageSharp/Primitives/Size.cs b/src/ImageSharp/Primitives/Size.cs index 83bd392139..0e55b6845e 100644 --- a/src/ImageSharp/Primitives/Size.cs +++ b/src/ImageSharp/Primitives/Size.cs @@ -20,7 +20,7 @@ namespace SixLabors.ImageSharp /// /// Represents a that has Width and Height values set to zero. /// - public static readonly Size Empty = default; + public static readonly Size Empty; /// /// Initializes a new instance of the struct. diff --git a/src/ImageSharp/Primitives/SizeF.cs b/src/ImageSharp/Primitives/SizeF.cs index 4e2fba4e9f..fed62e5120 100644 --- a/src/ImageSharp/Primitives/SizeF.cs +++ b/src/ImageSharp/Primitives/SizeF.cs @@ -20,7 +20,7 @@ namespace SixLabors.ImageSharp /// /// Represents a that has Width and Height values set to zero. /// - public static readonly SizeF Empty = default; + public static readonly SizeF Empty; /// /// Initializes a new instance of the struct. @@ -78,7 +78,7 @@ namespace SixLabors.ImageSharp /// The . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator Vector2(SizeF point) => new Vector2(point.Width, point.Height); + public static implicit operator Vector2(SizeF point) => new(point.Width, point.Height); /// /// Creates a with the dimensions of the specified by truncating each of the dimensions. @@ -88,14 +88,14 @@ namespace SixLabors.ImageSharp /// The . /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static explicit operator Size(SizeF size) => new Size(unchecked((int)size.Width), unchecked((int)size.Height)); + public static explicit operator Size(SizeF size) => new(unchecked((int)size.Width), unchecked((int)size.Height)); /// /// Converts the given into a . /// /// The size. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static explicit operator PointF(SizeF size) => new PointF(size.Width, size.Height); + public static explicit operator PointF(SizeF size) => new(size.Width, size.Height); /// /// Computes the sum of adding two sizes. @@ -142,7 +142,7 @@ namespace SixLabors.ImageSharp /// Divisor of type . /// Result of type . public static SizeF operator /(SizeF left, float right) - => new SizeF(left.Width / right, left.Height / right); + => new(left.Width / right, left.Height / right); /// /// Compares two objects for equality. @@ -173,7 +173,7 @@ namespace SixLabors.ImageSharp /// The size on the right hand of the operand. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static SizeF Add(SizeF left, SizeF right) => new SizeF(left.Width + right.Width, left.Height + right.Height); + public static SizeF Add(SizeF left, SizeF right) => new(left.Width + right.Width, left.Height + right.Height); /// /// Contracts a by another . @@ -182,7 +182,7 @@ namespace SixLabors.ImageSharp /// The size on the right hand of the operand. /// The . [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static SizeF Subtract(SizeF left, SizeF right) => new SizeF(left.Width - right.Width, left.Height - right.Height); + public static SizeF Subtract(SizeF left, SizeF right) => new(left.Width - right.Width, left.Height - right.Height); /// /// Transforms a size by the given matrix. @@ -228,6 +228,6 @@ namespace SixLabors.ImageSharp /// Multiplier of type . /// Product of type SizeF. private static SizeF Multiply(SizeF size, float multiplier) => - new SizeF(size.Width * multiplier, size.Height * multiplier); + new(size.Width * multiplier, size.Height * multiplier); } } diff --git a/src/ImageSharp/Processing/Processors/Convolution/KernelSamplingMap.cs b/src/ImageSharp/Processing/Processors/Convolution/KernelSamplingMap.cs index a455df412d..a4ae9cb4c6 100644 --- a/src/ImageSharp/Processing/Processors/Convolution/KernelSamplingMap.cs +++ b/src/ImageSharp/Processing/Processors/Convolution/KernelSamplingMap.cs @@ -60,8 +60,8 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution int minX = bounds.X; int maxX = bounds.Right - 1; - this.BuildOffsets(this.yOffsets, bounds.Height, kernelHeight, minY, maxY, yBorderMode); - this.BuildOffsets(this.xOffsets, bounds.Width, kernelWidth, minX, maxX, xBorderMode); + BuildOffsets(this.yOffsets, bounds.Height, kernelHeight, minY, maxY, yBorderMode); + BuildOffsets(this.xOffsets, bounds.Width, kernelWidth, minX, maxX, xBorderMode); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -83,7 +83,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void BuildOffsets(IMemoryOwner offsets, int boundsSize, int kernelSize, int min, int max, BorderWrappingMode borderMode) + private static void BuildOffsets(IMemoryOwner offsets, int boundsSize, int kernelSize, int min, int max, BorderWrappingMode borderMode) { int radius = kernelSize >> 1; Span span = offsets.GetSpan(); @@ -97,13 +97,13 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution } } - this.CorrectBorder(span, kernelSize, min, max, borderMode); + CorrectBorder(span, kernelSize, min, max, borderMode); } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void CorrectBorder(Span span, int kernelSize, int min, int max, BorderWrappingMode borderMode) + private static void CorrectBorder(Span span, int kernelSize, int min, int max, BorderWrappingMode borderMode) { - var affectedSize = (kernelSize >> 1) * kernelSize; + int affectedSize = (kernelSize >> 1) * kernelSize; ref int spanBase = ref MemoryMarshal.GetReference(span); if (affectedSize > 0) { @@ -114,20 +114,20 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution Numerics.Clamp(span[^affectedSize..], min, max); break; case BorderWrappingMode.Mirror: - var min2dec = min + min - 1; + int min2dec = min + min - 1; for (int i = 0; i < affectedSize; i++) { - var value = span[i]; + int value = span[i]; if (value < min) { span[i] = min2dec - value; } } - var max2inc = max + max + 1; + int max2inc = max + max + 1; for (int i = span.Length - affectedSize; i < span.Length; i++) { - var value = span[i]; + int value = span[i]; if (value > max) { span[i] = max2inc - value; @@ -136,20 +136,20 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution break; case BorderWrappingMode.Bounce: - var min2 = min + min; + int min2 = min + min; for (int i = 0; i < affectedSize; i++) { - var value = span[i]; + int value = span[i]; if (value < min) { span[i] = min2 - value; } } - var max2 = max + max; + int max2 = max + max; for (int i = span.Length - affectedSize; i < span.Length; i++) { - var value = span[i]; + int value = span[i]; if (value > max) { span[i] = max2 - value; @@ -158,10 +158,10 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution break; case BorderWrappingMode.Wrap: - var diff = max - min + 1; + int diff = max - min + 1; for (int i = 0; i < affectedSize; i++) { - var value = span[i]; + int value = span[i]; if (value < min) { span[i] = diff + value; @@ -170,7 +170,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution for (int i = span.Length - affectedSize; i < span.Length; i++) { - var value = span[i]; + int value = span[i]; if (value > max) { span[i] = value - diff; diff --git a/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetector2DKernel.cs b/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetector2DKernel.cs index 90c2575fc2..ff1bba22d2 100644 --- a/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetector2DKernel.cs +++ b/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetector2DKernel.cs @@ -13,30 +13,30 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution /// /// An edge detection kernel containing two Kayyali operators. /// - public static EdgeDetector2DKernel KayyaliKernel = new EdgeDetector2DKernel(KayyaliKernels.KayyaliX, KayyaliKernels.KayyaliY); + public static readonly EdgeDetector2DKernel KayyaliKernel = new(KayyaliKernels.KayyaliX, KayyaliKernels.KayyaliY); /// /// An edge detection kernel containing two Prewitt operators. /// . /// - public static EdgeDetector2DKernel PrewittKernel = new EdgeDetector2DKernel(PrewittKernels.PrewittX, PrewittKernels.PrewittY); + public static readonly EdgeDetector2DKernel PrewittKernel = new(PrewittKernels.PrewittX, PrewittKernels.PrewittY); /// /// An edge detection kernel containing two Roberts-Cross operators. /// . /// - public static EdgeDetector2DKernel RobertsCrossKernel = new EdgeDetector2DKernel(RobertsCrossKernels.RobertsCrossX, RobertsCrossKernels.RobertsCrossY); + public static readonly EdgeDetector2DKernel RobertsCrossKernel = new(RobertsCrossKernels.RobertsCrossX, RobertsCrossKernels.RobertsCrossY); /// /// An edge detection kernel containing two Scharr operators. /// - public static EdgeDetector2DKernel ScharrKernel = new EdgeDetector2DKernel(ScharrKernels.ScharrX, ScharrKernels.ScharrY); + public static readonly EdgeDetector2DKernel ScharrKernel = new(ScharrKernels.ScharrX, ScharrKernels.ScharrY); /// /// An edge detection kernel containing two Sobel operators. /// . /// - public static EdgeDetector2DKernel SobelKernel = new EdgeDetector2DKernel(SobelKernels.SobelX, SobelKernels.SobelY); + public static readonly EdgeDetector2DKernel SobelKernel = new(SobelKernels.SobelX, SobelKernels.SobelY); /// /// Initializes a new instance of the struct. diff --git a/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetectorCompassKernel.cs b/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetectorCompassKernel.cs index 002f35c3d3..41d3c8ad24 100644 --- a/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetectorCompassKernel.cs +++ b/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetectorCompassKernel.cs @@ -14,8 +14,8 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution /// An edge detection kenel comprised of Kirsch gradient operators. /// . /// - public static EdgeDetectorCompassKernel Kirsch = - new EdgeDetectorCompassKernel( + public static readonly EdgeDetectorCompassKernel Kirsch = + new( KirschKernels.North, KirschKernels.NorthWest, KirschKernels.West, @@ -29,8 +29,8 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution /// An edge detection kenel comprised of Robinson gradient operators. /// /// - public static EdgeDetectorCompassKernel Robinson = - new EdgeDetectorCompassKernel( + public static readonly EdgeDetectorCompassKernel Robinson = + new( RobinsonKernels.North, RobinsonKernels.NorthWest, RobinsonKernels.West, diff --git a/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetectorKernel.cs b/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetectorKernel.cs index 0640884324..25007846c9 100644 --- a/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetectorKernel.cs +++ b/src/ImageSharp/Processing/Processors/Convolution/Kernels/EdgeDetectorKernel.cs @@ -14,19 +14,19 @@ namespace SixLabors.ImageSharp.Processing.Processors.Convolution /// An edge detection kernel containing a 3x3 Laplacian operator. /// /// - public static EdgeDetectorKernel Laplacian3x3 = new EdgeDetectorKernel(LaplacianKernels.Laplacian3x3); + public static readonly EdgeDetectorKernel Laplacian3x3 = new(LaplacianKernels.Laplacian3x3); /// /// An edge detection kernel containing a 5x5 Laplacian operator. /// /// - public static EdgeDetectorKernel Laplacian5x5 = new EdgeDetectorKernel(LaplacianKernels.Laplacian5x5); + public static readonly EdgeDetectorKernel Laplacian5x5 = new(LaplacianKernels.Laplacian5x5); /// /// An edge detection kernel containing a Laplacian of Gaussian operator. /// . /// - public static EdgeDetectorKernel LaplacianOfGaussian = new EdgeDetectorKernel(LaplacianKernels.LaplacianOfGaussianXY); + public static readonly EdgeDetectorKernel LaplacianOfGaussian = new(LaplacianKernels.LaplacianOfGaussianXY); /// /// Initializes a new instance of the struct. diff --git a/src/ImageSharp/Processing/Processors/Dithering/ErroDither.KnownTypes.cs b/src/ImageSharp/Processing/Processors/Dithering/ErroDither.KnownTypes.cs index 435cafb520..2c9ce24194 100644 --- a/src/ImageSharp/Processing/Processors/Dithering/ErroDither.KnownTypes.cs +++ b/src/ImageSharp/Processing/Processors/Dithering/ErroDither.KnownTypes.cs @@ -11,178 +11,178 @@ namespace SixLabors.ImageSharp.Processing.Processors.Dithering /// /// Applies error diffusion based dithering using the Atkinson image dithering algorithm. /// - public static ErrorDither Atkinson = CreateAtkinson(); + public static readonly ErrorDither Atkinson = CreateAtkinson(); /// /// Applies error diffusion based dithering using the Burks image dithering algorithm. /// - public static ErrorDither Burkes = CreateBurks(); + public static readonly ErrorDither Burkes = CreateBurks(); /// /// Applies error diffusion based dithering using the Floyd–Steinberg image dithering algorithm. /// - public static ErrorDither FloydSteinberg = CreateFloydSteinberg(); + public static readonly ErrorDither FloydSteinberg = CreateFloydSteinberg(); /// /// Applies error diffusion based dithering using the Jarvis, Judice, Ninke image dithering algorithm. /// - public static ErrorDither JarvisJudiceNinke = CreateJarvisJudiceNinke(); + public static readonly ErrorDither JarvisJudiceNinke = CreateJarvisJudiceNinke(); /// /// Applies error diffusion based dithering using the Sierra2 image dithering algorithm. /// - public static ErrorDither Sierra2 = CreateSierra2(); + public static readonly ErrorDither Sierra2 = CreateSierra2(); /// /// Applies error diffusion based dithering using the Sierra3 image dithering algorithm. /// - public static ErrorDither Sierra3 = CreateSierra3(); + public static readonly ErrorDither Sierra3 = CreateSierra3(); /// /// Applies error diffusion based dithering using the Sierra Lite image dithering algorithm. /// - public static ErrorDither SierraLite = CreateSierraLite(); + public static readonly ErrorDither SierraLite = CreateSierraLite(); /// /// Applies error diffusion based dithering using the Stevenson-Arce image dithering algorithm. /// - public static ErrorDither StevensonArce = CreateStevensonArce(); + public static readonly ErrorDither StevensonArce = CreateStevensonArce(); /// /// Applies error diffusion based dithering using the Stucki image dithering algorithm. /// - public static ErrorDither Stucki = CreateStucki(); + public static readonly ErrorDither Stucki = CreateStucki(); private static ErrorDither CreateAtkinson() { - const float Divisor = 8F; - const int Offset = 1; + const float divisor = 8F; + const int offset = 1; - var matrix = new float[,] + float[,] matrix = { - { 0, 0, 1 / Divisor, 1 / Divisor }, - { 1 / Divisor, 1 / Divisor, 1 / Divisor, 0 }, - { 0, 1 / Divisor, 0, 0 } + { 0, 0, 1 / divisor, 1 / divisor }, + { 1 / divisor, 1 / divisor, 1 / divisor, 0 }, + { 0, 1 / divisor, 0, 0 } }; - return new ErrorDither(matrix, Offset); + return new ErrorDither(matrix, offset); } private static ErrorDither CreateBurks() { - const float Divisor = 32F; - const int Offset = 2; + const float divisor = 32F; + const int offset = 2; - var matrix = new float[,] + float[,] matrix = { - { 0, 0, 0, 8 / Divisor, 4 / Divisor }, - { 2 / Divisor, 4 / Divisor, 8 / Divisor, 4 / Divisor, 2 / Divisor } + { 0, 0, 0, 8 / divisor, 4 / divisor }, + { 2 / divisor, 4 / divisor, 8 / divisor, 4 / divisor, 2 / divisor } }; - return new ErrorDither(matrix, Offset); + return new ErrorDither(matrix, offset); } private static ErrorDither CreateFloydSteinberg() { - const float Divisor = 16F; - const int Offset = 1; + const float divisor = 16F; + const int offset = 1; - var matrix = new float[,] + float[,] matrix = { - { 0, 0, 7 / Divisor }, - { 3 / Divisor, 5 / Divisor, 1 / Divisor } + { 0, 0, 7 / divisor }, + { 3 / divisor, 5 / divisor, 1 / divisor } }; - return new ErrorDither(matrix, Offset); + return new ErrorDither(matrix, offset); } private static ErrorDither CreateJarvisJudiceNinke() { - const float Divisor = 48F; - const int Offset = 2; + const float divisor = 48F; + const int offset = 2; - var matrix = new float[,] + float[,] matrix = { - { 0, 0, 0, 7 / Divisor, 5 / Divisor }, - { 3 / Divisor, 5 / Divisor, 7 / Divisor, 5 / Divisor, 3 / Divisor }, - { 1 / Divisor, 3 / Divisor, 5 / Divisor, 3 / Divisor, 1 / Divisor } + { 0, 0, 0, 7 / divisor, 5 / divisor }, + { 3 / divisor, 5 / divisor, 7 / divisor, 5 / divisor, 3 / divisor }, + { 1 / divisor, 3 / divisor, 5 / divisor, 3 / divisor, 1 / divisor } }; - return new ErrorDither(matrix, Offset); + return new ErrorDither(matrix, offset); } private static ErrorDither CreateSierra2() { - const float Divisor = 16F; - const int Offset = 2; + const float divisor = 16F; + const int offset = 2; - var matrix = new float[,] + float[,] matrix = { - { 0, 0, 0, 4 / Divisor, 3 / Divisor }, - { 1 / Divisor, 2 / Divisor, 3 / Divisor, 2 / Divisor, 1 / Divisor } + { 0, 0, 0, 4 / divisor, 3 / divisor }, + { 1 / divisor, 2 / divisor, 3 / divisor, 2 / divisor, 1 / divisor } }; - return new ErrorDither(matrix, Offset); + return new ErrorDither(matrix, offset); } private static ErrorDither CreateSierra3() { - const float Divisor = 32F; - const int Offset = 2; + const float divisor = 32F; + const int offset = 2; - var matrix = new float[,] + float[,] matrix = { - { 0, 0, 0, 5 / Divisor, 3 / Divisor }, - { 2 / Divisor, 4 / Divisor, 5 / Divisor, 4 / Divisor, 2 / Divisor }, - { 0, 2 / Divisor, 3 / Divisor, 2 / Divisor, 0 } + { 0, 0, 0, 5 / divisor, 3 / divisor }, + { 2 / divisor, 4 / divisor, 5 / divisor, 4 / divisor, 2 / divisor }, + { 0, 2 / divisor, 3 / divisor, 2 / divisor, 0 } }; - return new ErrorDither(matrix, Offset); + return new ErrorDither(matrix, offset); } private static ErrorDither CreateSierraLite() { - const float Divisor = 4F; - const int Offset = 1; + const float divisor = 4F; + const int offset = 1; - var matrix = new float[,] + float[,] matrix = { - { 0, 0, 2 / Divisor }, - { 1 / Divisor, 1 / Divisor, 0 } + { 0, 0, 2 / divisor }, + { 1 / divisor, 1 / divisor, 0 } }; - return new ErrorDither(matrix, Offset); + return new ErrorDither(matrix, offset); } private static ErrorDither CreateStevensonArce() { - const float Divisor = 200F; - const int Offset = 3; + const float divisor = 200F; + const int offset = 3; - var matrix = new float[,] + float[,] matrix = { - { 0, 0, 0, 0, 0, 32 / Divisor, 0 }, - { 12 / Divisor, 0, 26 / Divisor, 0, 30 / Divisor, 0, 16 / Divisor }, - { 0, 12 / Divisor, 0, 26 / Divisor, 0, 12 / Divisor, 0 }, - { 5 / Divisor, 0, 12 / Divisor, 0, 12 / Divisor, 0, 5 / Divisor } + { 0, 0, 0, 0, 0, 32 / divisor, 0 }, + { 12 / divisor, 0, 26 / divisor, 0, 30 / divisor, 0, 16 / divisor }, + { 0, 12 / divisor, 0, 26 / divisor, 0, 12 / divisor, 0 }, + { 5 / divisor, 0, 12 / divisor, 0, 12 / divisor, 0, 5 / divisor } }; - return new ErrorDither(matrix, Offset); + return new ErrorDither(matrix, offset); } private static ErrorDither CreateStucki() { - const float Divisor = 42F; - const int Offset = 2; + const float divisor = 42F; + const int offset = 2; - var matrix = new float[,] + float[,] matrix = { - { 0, 0, 0, 8 / Divisor, 4 / Divisor }, - { 2 / Divisor, 4 / Divisor, 8 / Divisor, 4 / Divisor, 2 / Divisor }, - { 1 / Divisor, 2 / Divisor, 4 / Divisor, 2 / Divisor, 1 / Divisor } + { 0, 0, 0, 8 / divisor, 4 / divisor }, + { 2 / divisor, 4 / divisor, 8 / divisor, 4 / divisor, 2 / divisor }, + { 1 / divisor, 2 / divisor, 4 / divisor, 2 / divisor, 1 / divisor } }; - return new ErrorDither(matrix, Offset); + return new ErrorDither(matrix, offset); } } } diff --git a/src/ImageSharp/Processing/Processors/Dithering/OrderedDither.KnownTypes.cs b/src/ImageSharp/Processing/Processors/Dithering/OrderedDither.KnownTypes.cs index a6838d246f..f036273c2e 100644 --- a/src/ImageSharp/Processing/Processors/Dithering/OrderedDither.KnownTypes.cs +++ b/src/ImageSharp/Processing/Processors/Dithering/OrderedDither.KnownTypes.cs @@ -11,26 +11,26 @@ namespace SixLabors.ImageSharp.Processing.Processors.Dithering /// /// Applies order dithering using the 2x2 Bayer dithering matrix. /// - public static OrderedDither Bayer2x2 = new OrderedDither(2); + public static readonly OrderedDither Bayer2x2 = new(2); /// /// Applies order dithering using the 4x4 Bayer dithering matrix. /// - public static OrderedDither Bayer4x4 = new OrderedDither(4); + public static readonly OrderedDither Bayer4x4 = new(4); /// /// Applies order dithering using the 8x8 Bayer dithering matrix. /// - public static OrderedDither Bayer8x8 = new OrderedDither(8); + public static readonly OrderedDither Bayer8x8 = new(8); /// /// Applies order dithering using the 16x16 Bayer dithering matrix. /// - public static OrderedDither Bayer16x16 = new OrderedDither(16); + public static readonly OrderedDither Bayer16x16 = new(16); /// /// Applies order dithering using the 3x3 ordered dithering matrix. /// - public static OrderedDither Ordered3x3 = new OrderedDither(3); + public static readonly OrderedDither Ordered3x3 = new(3); } } diff --git a/src/ImageSharp/Processing/Processors/Dithering/PaletteDitherProcessor{TPixel}.cs b/src/ImageSharp/Processing/Processors/Dithering/PaletteDitherProcessor{TPixel}.cs index 248c216410..4933b9f755 100644 --- a/src/ImageSharp/Processing/Processors/Dithering/PaletteDitherProcessor{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Dithering/PaletteDitherProcessor{TPixel}.cs @@ -3,6 +3,7 @@ using System; using System.Buffers; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors.Quantization; @@ -35,7 +36,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Dithering ReadOnlySpan sourcePalette = definition.Palette.Span; this.paletteOwner = this.Configuration.MemoryAllocator.Allocate(sourcePalette.Length); - Color.ToPixel(this.Configuration, sourcePalette, this.paletteOwner.Memory.Span); + Color.ToPixel(sourcePalette, this.paletteOwner.Memory.Span); this.ditherProcessor = new DitherProcessor( this.Configuration, @@ -46,7 +47,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Dithering /// protected override void OnFrameApply(ImageFrame source) { - var interest = Rectangle.Intersect(this.SourceRectangle, source.Bounds()); + Rectangle interest = Rectangle.Intersect(this.SourceRectangle, source.Bounds()); this.dither.ApplyPaletteDither(in this.ditherProcessor, source, interest); } @@ -74,6 +75,10 @@ namespace SixLabors.ImageSharp.Processing.Processors.Dithering /// . /// /// Internal for AOT + [SuppressMessage( + "Design", + "CA1001:Types that own disposable fields should be disposable", + Justification = "https://github.com/dotnet/roslyn-analyzers/issues/6151")] internal readonly struct DitherProcessor : IPaletteDitherImageProcessor, IDisposable { private readonly EuclideanPixelMap pixelMap; diff --git a/src/ImageSharp/Processing/Processors/Effects/OilPaintingProcessor{TPixel}.cs b/src/ImageSharp/Processing/Processors/Effects/OilPaintingProcessor{TPixel}.cs index cf56d03389..4d33b848b1 100644 --- a/src/ImageSharp/Processing/Processors/Effects/OilPaintingProcessor{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Effects/OilPaintingProcessor{TPixel}.cs @@ -30,24 +30,18 @@ namespace SixLabors.ImageSharp.Processing.Processors.Effects /// The source area to process for the current processor instance. public OilPaintingProcessor(Configuration configuration, OilPaintingProcessor definition, Image source, Rectangle sourceRectangle) : base(configuration, source, sourceRectangle) - { - this.definition = definition; - } + => this.definition = definition; /// protected override void OnFrameApply(ImageFrame source) { - int brushSize = this.definition.BrushSize; - if (brushSize <= 0 || brushSize > source.Height || brushSize > source.Width) - { - throw new ArgumentOutOfRangeException(nameof(brushSize)); - } + int brushSize = Math.Clamp(this.definition.BrushSize, 1, Math.Min(source.Width, source.Height)); using Buffer2D targetPixels = this.Configuration.MemoryAllocator.Allocate2D(source.Size()); source.CopyTo(targetPixels); - var operation = new RowIntervalOperation(this.SourceRectangle, targetPixels, source.PixelBuffer, this.Configuration, brushSize >> 1, this.definition.Levels); + RowIntervalOperation operation = new(this.SourceRectangle, targetPixels, source.PixelBuffer, this.Configuration, brushSize >> 1, this.definition.Levels); ParallelRowIterator.IterateRowIntervals( this.Configuration, this.SourceRectangle, @@ -147,7 +141,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Effects int offsetX = x + fxr; offsetX = Numerics.Clamp(offsetX, 0, maxX); - var vector = sourceOffsetRow[offsetX].ToVector4(); + Vector4 vector = sourceOffsetRow[offsetX].ToVector4(); float sourceRed = vector.X; float sourceBlue = vector.Z; diff --git a/src/ImageSharp/Processing/Processors/Normalization/AdaptiveHistogramEqualizationProcessor{TPixel}.cs b/src/ImageSharp/Processing/Processors/Normalization/AdaptiveHistogramEqualizationProcessor{TPixel}.cs index d6d69f1617..518b19c4ca 100644 --- a/src/ImageSharp/Processing/Processors/Normalization/AdaptiveHistogramEqualizationProcessor{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Normalization/AdaptiveHistogramEqualizationProcessor{TPixel}.cs @@ -628,7 +628,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization this.processor.ClipHistogram(histogram, this.processor.ClipLimit); } - cdfMinSpan[cdfX] += this.processor.CalculateCdf(ref cdfBase, ref histogramBase, histogram.Length - 1); + cdfMinSpan[cdfX] += CalculateCdf(ref cdfBase, ref histogramBase, histogram.Length - 1); cdfX++; } diff --git a/src/ImageSharp/Processing/Processors/Normalization/AdaptiveHistogramEqualizationSlidingWindowProcessor{TPixel}.cs b/src/ImageSharp/Processing/Processors/Normalization/AdaptiveHistogramEqualizationSlidingWindowProcessor{TPixel}.cs index a2f346be01..b7e5819e0e 100644 --- a/src/ImageSharp/Processing/Processors/Normalization/AdaptiveHistogramEqualizationSlidingWindowProcessor{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Normalization/AdaptiveHistogramEqualizationSlidingWindowProcessor{TPixel}.cs @@ -7,7 +7,6 @@ using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading.Tasks; -using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; @@ -57,20 +56,21 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization { MemoryAllocator memoryAllocator = this.Configuration.MemoryAllocator; - var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = this.Configuration.MaxDegreeOfParallelism }; + ParallelOptions parallelOptions = new() + { MaxDegreeOfParallelism = this.Configuration.MaxDegreeOfParallelism }; int tileWidth = source.Width / this.Tiles; int tileHeight = tileWidth; int pixelInTile = tileWidth * tileHeight; int halfTileHeight = tileHeight / 2; int halfTileWidth = halfTileHeight; - var slidingWindowInfos = new SlidingWindowInfos(tileWidth, tileHeight, halfTileWidth, halfTileHeight, pixelInTile); + SlidingWindowInfos slidingWindowInfos = new(tileWidth, tileHeight, halfTileWidth, halfTileHeight, pixelInTile); // TODO: If the process was able to be switched to operate in parallel rows instead of columns // then we could take advantage of batching and allocate per-row buffers only once per batch. using Buffer2D targetPixels = this.Configuration.MemoryAllocator.Allocate2D(source.Width, source.Height); // Process the inner tiles, which do not require to check the borders. - var innerOperation = new SlidingWindowOperation( + SlidingWindowOperation innerOperation = new( this.Configuration, this, source, @@ -88,7 +88,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization innerOperation.Invoke); // Process the left border of the image. - var leftBorderOperation = new SlidingWindowOperation( + SlidingWindowOperation leftBorderOperation = new( this.Configuration, this, source, @@ -106,7 +106,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization leftBorderOperation.Invoke); // Process the right border of the image. - var rightBorderOperation = new SlidingWindowOperation( + SlidingWindowOperation rightBorderOperation = new( this.Configuration, this, source, @@ -124,7 +124,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization rightBorderOperation.Invoke); // Process the top border of the image. - var topBorderOperation = new SlidingWindowOperation( + SlidingWindowOperation topBorderOperation = new( this.Configuration, this, source, @@ -142,7 +142,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization topBorderOperation.Invoke); // Process the bottom border of the image. - var bottomBorderOperation = new SlidingWindowOperation( + SlidingWindowOperation bottomBorderOperation = new( this.Configuration, this, source, @@ -171,7 +171,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization /// The y position. /// The width in pixels of a tile. /// The configuration. - private void CopyPixelRow( + private static void CopyPixelRow( ImageFrame source, Span rowPixels, int x, @@ -224,7 +224,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization return; } - this.CopyPixelRowFast(source.PixelBuffer, rowPixels, x, y, tileWidth, configuration); + CopyPixelRowFast(source.PixelBuffer, rowPixels, x, y, tileWidth, configuration); } /// @@ -237,7 +237,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization /// The width in pixels of a tile. /// The configuration. [MethodImpl(InliningOptions.ShortMethod)] - private void CopyPixelRowFast( + private static void CopyPixelRowFast( Buffer2D source, Span rowPixels, int x, @@ -254,7 +254,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization /// The number of different luminance levels. /// The grey values span length. [MethodImpl(InliningOptions.ShortMethod)] - private void AddPixelsToHistogram(ref Vector4 greyValuesBase, ref int histogramBase, int luminanceLevels, int length) + private static void AddPixelsToHistogram(ref Vector4 greyValuesBase, ref int histogramBase, int luminanceLevels, int length) { for (nint idx = 0; idx < length; idx++) { @@ -271,7 +271,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization /// The number of different luminance levels. /// The grey values span length. [MethodImpl(InliningOptions.ShortMethod)] - private void RemovePixelsFromHistogram(ref Vector4 greyValuesBase, ref int histogramBase, int luminanceLevels, int length) + private static void RemovePixelsFromHistogram(ref Vector4 greyValuesBase, ref int histogramBase, int luminanceLevels, int length) { for (int idx = 0; idx < length; idx++) { @@ -356,14 +356,14 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization { if (this.useFastPath) { - this.processor.CopyPixelRowFast(this.source.PixelBuffer, pixelRow, x - this.swInfos.HalfTileWidth, dy, this.swInfos.TileWidth, this.configuration); + CopyPixelRowFast(this.source.PixelBuffer, pixelRow, x - this.swInfos.HalfTileWidth, dy, this.swInfos.TileWidth, this.configuration); } else { - this.processor.CopyPixelRow(this.source, pixelRow, x - this.swInfos.HalfTileWidth, dy, this.swInfos.TileWidth, this.configuration); + CopyPixelRow(this.source, pixelRow, x - this.swInfos.HalfTileWidth, dy, this.swInfos.TileWidth, this.configuration); } - this.processor.AddPixelsToHistogram(ref pixelRowBase, ref histogramBase, this.processor.LuminanceLevels, pixelRow.Length); + AddPixelsToHistogram(ref pixelRowBase, ref histogramBase, this.processor.LuminanceLevels, pixelRow.Length); } for (int y = this.yStart; y < this.yEnd; y++) @@ -377,8 +377,8 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization // Calculate the cumulative distribution function, which will map each input pixel in the current tile to a new value. int cdfMin = this.processor.ClipHistogramEnabled - ? this.processor.CalculateCdf(ref cdfBase, ref histogramCopyBase, histogram.Length - 1) - : this.processor.CalculateCdf(ref cdfBase, ref histogramBase, histogram.Length - 1); + ? CalculateCdf(ref cdfBase, ref histogramCopyBase, histogram.Length - 1) + : CalculateCdf(ref cdfBase, ref histogramBase, histogram.Length - 1); float numberOfPixelsMinusCdfMin = this.swInfos.PixelInTile - cdfMin; @@ -390,26 +390,26 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization // Remove top most row from the histogram, mirroring rows which exceeds the borders. if (this.useFastPath) { - this.processor.CopyPixelRowFast(this.source.PixelBuffer, pixelRow, x - this.swInfos.HalfTileWidth, y - this.swInfos.HalfTileWidth, this.swInfos.TileWidth, this.configuration); + CopyPixelRowFast(this.source.PixelBuffer, pixelRow, x - this.swInfos.HalfTileWidth, y - this.swInfos.HalfTileWidth, this.swInfos.TileWidth, this.configuration); } else { - this.processor.CopyPixelRow(this.source, pixelRow, x - this.swInfos.HalfTileWidth, y - this.swInfos.HalfTileWidth, this.swInfos.TileWidth, this.configuration); + CopyPixelRow(this.source, pixelRow, x - this.swInfos.HalfTileWidth, y - this.swInfos.HalfTileWidth, this.swInfos.TileWidth, this.configuration); } - this.processor.RemovePixelsFromHistogram(ref pixelRowBase, ref histogramBase, this.processor.LuminanceLevels, pixelRow.Length); + RemovePixelsFromHistogram(ref pixelRowBase, ref histogramBase, this.processor.LuminanceLevels, pixelRow.Length); // Add new bottom row to the histogram, mirroring rows which exceeds the borders. if (this.useFastPath) { - this.processor.CopyPixelRowFast(this.source.PixelBuffer, pixelRow, x - this.swInfos.HalfTileWidth, y + this.swInfos.HalfTileWidth, this.swInfos.TileWidth, this.configuration); + CopyPixelRowFast(this.source.PixelBuffer, pixelRow, x - this.swInfos.HalfTileWidth, y + this.swInfos.HalfTileWidth, this.swInfos.TileWidth, this.configuration); } else { - this.processor.CopyPixelRow(this.source, pixelRow, x - this.swInfos.HalfTileWidth, y + this.swInfos.HalfTileWidth, this.swInfos.TileWidth, this.configuration); + CopyPixelRow(this.source, pixelRow, x - this.swInfos.HalfTileWidth, y + this.swInfos.HalfTileWidth, this.swInfos.TileWidth, this.configuration); } - this.processor.AddPixelsToHistogram(ref pixelRowBase, ref histogramBase, this.processor.LuminanceLevels, pixelRow.Length); + AddPixelsToHistogram(ref pixelRowBase, ref histogramBase, this.processor.LuminanceLevels, pixelRow.Length); } } } diff --git a/src/ImageSharp/Processing/Processors/Normalization/GlobalHistogramEqualizationProcessor{TPixel}.cs b/src/ImageSharp/Processing/Processors/Normalization/GlobalHistogramEqualizationProcessor{TPixel}.cs index c27118be4e..c4b925efed 100644 --- a/src/ImageSharp/Processing/Processors/Normalization/GlobalHistogramEqualizationProcessor{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Normalization/GlobalHistogramEqualizationProcessor{TPixel}.cs @@ -68,7 +68,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization using IMemoryOwner cdfBuffer = memoryAllocator.Allocate(this.LuminanceLevels, AllocationOptions.Clean); // Calculate the cumulative distribution function, which will map each input pixel to a new value. - int cdfMin = this.CalculateCdf( + int cdfMin = CalculateCdf( ref MemoryMarshal.GetReference(cdfBuffer.GetSpan()), ref MemoryMarshal.GetReference(histogram), histogram.Length - 1); diff --git a/src/ImageSharp/Processing/Processors/Normalization/HistogramEqualizationOptions.cs b/src/ImageSharp/Processing/Processors/Normalization/HistogramEqualizationOptions.cs index 71fbc6e5be..0e9bfa7e48 100644 --- a/src/ImageSharp/Processing/Processors/Normalization/HistogramEqualizationOptions.cs +++ b/src/ImageSharp/Processing/Processors/Normalization/HistogramEqualizationOptions.cs @@ -25,7 +25,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization /// It is recommended to use clipping when the AdaptiveTileInterpolation method is used, to suppress artifacts which can occur on the borders of the tiles. /// Defaults to false. /// - public bool ClipHistogram { get; set; } = false; + public bool ClipHistogram { get; set; } /// /// Gets or sets the histogram clip limit. Adaptive histogram equalization may cause noise to be amplified in near constant diff --git a/src/ImageSharp/Processing/Processors/Normalization/HistogramEqualizationProcessor{TPixel}.cs b/src/ImageSharp/Processing/Processors/Normalization/HistogramEqualizationProcessor{TPixel}.cs index 4c32c5fd92..0213799071 100644 --- a/src/ImageSharp/Processing/Processors/Normalization/HistogramEqualizationProcessor{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Normalization/HistogramEqualizationProcessor{TPixel}.cs @@ -2,6 +2,7 @@ // Licensed under the Six Labors Split License. using System; +using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using SixLabors.ImageSharp.PixelFormats; @@ -67,7 +68,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization /// The reference to the histogram of the input image. /// Index of the maximum of the histogram. /// The first none zero value of the cdf. - public int CalculateCdf(ref int cdfBase, ref int histogramBase, int maxIdx) + public static int CalculateCdf(ref int cdfBase, ref int histogramBase, int maxIdx) { int histSum = 0; int cdfMin = 0; @@ -142,7 +143,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Normalization public static int GetLuminance(TPixel sourcePixel, int luminanceLevels) { // TODO: We need a bulk per span equivalent. - var vector = sourcePixel.ToVector4(); + Vector4 vector = sourcePixel.ToVector4(); return ColorNumerics.GetBT709Luminance(ref vector, luminanceLevels); } } diff --git a/src/ImageSharp/Processing/Processors/Quantization/EuclideanPixelMap{TPixel}.cs b/src/ImageSharp/Processing/Processors/Quantization/EuclideanPixelMap{TPixel}.cs index 981e1cf607..d06661d07e 100644 --- a/src/ImageSharp/Processing/Processors/Quantization/EuclideanPixelMap{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Quantization/EuclideanPixelMap{TPixel}.cs @@ -23,7 +23,9 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization { private Rgba32[] rgbaPalette; - // Do not make this readonly! Struct value would be always copied on non-readonly method calls. + /// + /// Do not make this readonly! Struct value would be always copied on non-readonly method calls. + /// private ColorDistanceCache cache; private readonly Configuration configuration; diff --git a/src/ImageSharp/Processing/Processors/Quantization/OctreeQuantizer{TPixel}.cs b/src/ImageSharp/Processing/Processors/Quantization/OctreeQuantizer{TPixel}.cs index a066bfdc4a..b3aa58acf3 100644 --- a/src/ImageSharp/Processing/Processors/Quantization/OctreeQuantizer{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Quantization/OctreeQuantizer{TPixel}.cs @@ -3,6 +3,7 @@ using System; using System.Buffers; +using System.Diagnostics.CodeAnalysis; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -16,6 +17,10 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization /// /// /// The pixel format. + [SuppressMessage( + "Design", + "CA1001:Types that own disposable fields should be disposable", + Justification = "https://github.com/dotnet/roslyn-analyzers/issues/6151")] public struct OctreeQuantizer : IQuantizer where TPixel : unmanaged, IPixel { @@ -48,7 +53,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization this.paletteOwner = configuration.MemoryAllocator.Allocate(this.maxColors, AllocationOptions.Clean); this.pixelMap = default; this.palette = default; - this.isDithering = !(this.Options.Dither is null); + this.isDithering = this.Options.Dither is not null; this.isDisposed = false; } @@ -473,7 +478,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization if (this.leaf) { // Set the color of the palette entry - var vector = Vector3.Clamp( + Vector3 vector = Vector3.Clamp( new Vector3(this.red, this.green, this.blue) / this.pixelCount, Vector3.Zero, new Vector3(255)); diff --git a/src/ImageSharp/Processing/Processors/Quantization/PaletteQuantizer.cs b/src/ImageSharp/Processing/Processors/Quantization/PaletteQuantizer.cs index ab0f1548f8..cc4b4a33fe 100644 --- a/src/ImageSharp/Processing/Processors/Quantization/PaletteQuantizer.cs +++ b/src/ImageSharp/Processing/Processors/Quantization/PaletteQuantizer.cs @@ -54,9 +54,9 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization // since the palette is unchanging. This allows a reduction of memory usage across // multi frame gifs using a global palette. int length = Math.Min(this.colorPalette.Length, options.MaxColors); - var palette = new TPixel[length]; + TPixel[] palette = new TPixel[length]; - Color.ToPixel(configuration, this.colorPalette.Span, palette.AsSpan()); + Color.ToPixel(this.colorPalette.Span, palette.AsSpan()); return new PaletteQuantizer(configuration, options, palette); } } diff --git a/src/ImageSharp/Processing/Processors/Quantization/PaletteQuantizer{TPixel}.cs b/src/ImageSharp/Processing/Processors/Quantization/PaletteQuantizer{TPixel}.cs index 5196070e4f..1fcdbc5b1f 100644 --- a/src/ImageSharp/Processing/Processors/Quantization/PaletteQuantizer{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Quantization/PaletteQuantizer{TPixel}.cs @@ -2,6 +2,7 @@ // Licensed under the Six Labors Split License. using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; @@ -13,6 +14,10 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization /// /// /// The pixel format. + [SuppressMessage( + "Design", + "CA1001:Types that own disposable fields should be disposable", + Justification = "https://github.com/dotnet/roslyn-analyzers/issues/6151")] internal struct PaletteQuantizer : IQuantizer where TPixel : unmanaged, IPixel { diff --git a/src/ImageSharp/Processing/Processors/Quantization/WuQuantizer{TPixel}.cs b/src/ImageSharp/Processing/Processors/Quantization/WuQuantizer{TPixel}.cs index 39c753722c..5f04669b74 100644 --- a/src/ImageSharp/Processing/Processors/Quantization/WuQuantizer{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Quantization/WuQuantizer{TPixel}.cs @@ -3,6 +3,7 @@ using System; using System.Buffers; +using System.Diagnostics.CodeAnalysis; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -31,6 +32,10 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization /// /// /// The pixel format. + [SuppressMessage( + "Design", + "CA1001:Types that own disposable fields should be disposable", + Justification = "https://github.com/dotnet/roslyn-analyzers/issues/6151")] internal struct WuQuantizer : IQuantizer where TPixel : unmanaged, IPixel { @@ -97,7 +102,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization this.isDisposed = false; this.pixelMap = default; this.palette = default; - this.isDithering = this.isDithering = !(this.Options.Dither is null); + this.isDithering = this.isDithering = this.Options.Dither is not null; } /// @@ -256,58 +261,51 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization /// The direction. /// The moment. /// The result. + /// Invalid direction. private static Moment Bottom(ref Box cube, int direction, ReadOnlySpan moments) - { - switch (direction) + => direction switch { // Red - case 3: - return -moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMax, cube.AMax)] - + moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMax, cube.AMin)] - + moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, cube.AMax)] - - moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, cube.AMin)] - + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, cube.AMax)] - - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, cube.AMin)] - - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMax)] - + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMin)]; + 3 => -moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMax, cube.AMax)] + + moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMax, cube.AMin)] + + moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, cube.AMax)] + - moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, cube.AMin)] + + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, cube.AMax)] + - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, cube.AMin)] + - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMax)] + + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMin)], // Green - case 2: - return -moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMax, cube.AMax)] - + moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMax, cube.AMin)] - + moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, cube.AMax)] - - moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, cube.AMin)] - + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, cube.AMax)] - - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, cube.AMin)] - - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMax)] - + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMin)]; + 2 => -moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMax, cube.AMax)] + + moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMax, cube.AMin)] + + moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, cube.AMax)] + - moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, cube.AMin)] + + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, cube.AMax)] + - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, cube.AMin)] + - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMax)] + + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMin)], // Blue - case 1: - return -moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMin, cube.AMax)] - + moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMin, cube.AMin)] - + moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, cube.AMax)] - - moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, cube.AMin)] - + moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, cube.AMax)] - - moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, cube.AMin)] - - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMax)] - + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMin)]; + 1 => -moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMin, cube.AMax)] + + moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMin, cube.AMin)] + + moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, cube.AMax)] + - moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, cube.AMin)] + + moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, cube.AMax)] + - moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, cube.AMin)] + - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMax)] + + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMin)], // Alpha - case 0: - return -moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMax, cube.AMin)] - + moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMin, cube.AMin)] - + moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMax, cube.AMin)] - - moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, cube.AMin)] - + moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMax, cube.AMin)] - - moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, cube.AMin)] - - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, cube.AMin)] - + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMin)]; - - default: - throw new ArgumentOutOfRangeException(nameof(direction)); - } - } + 0 => -moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMax, cube.AMin)] + + moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMin, cube.AMin)] + + moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMax, cube.AMin)] + - moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, cube.AMin)] + + moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMax, cube.AMin)] + - moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, cube.AMin)] + - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, cube.AMin)] + + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMin)], + _ => throw new ArgumentOutOfRangeException(nameof(direction)), + }; /// /// Computes remainder of Volume(cube, moment), substituting position for RMax, GMax, BMax, or AMax (depending on direction). @@ -317,58 +315,51 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization /// The position. /// The moment. /// The result. + /// Invalid direction. private static Moment Top(ref Box cube, int direction, int position, ReadOnlySpan moments) - { - switch (direction) + => direction switch { // Red - case 3: - return moments[GetPaletteIndex(position, cube.GMax, cube.BMax, cube.AMax)] - - moments[GetPaletteIndex(position, cube.GMax, cube.BMax, cube.AMin)] - - moments[GetPaletteIndex(position, cube.GMax, cube.BMin, cube.AMax)] - + moments[GetPaletteIndex(position, cube.GMax, cube.BMin, cube.AMin)] - - moments[GetPaletteIndex(position, cube.GMin, cube.BMax, cube.AMax)] - + moments[GetPaletteIndex(position, cube.GMin, cube.BMax, cube.AMin)] - + moments[GetPaletteIndex(position, cube.GMin, cube.BMin, cube.AMax)] - - moments[GetPaletteIndex(position, cube.GMin, cube.BMin, cube.AMin)]; + 3 => moments[GetPaletteIndex(position, cube.GMax, cube.BMax, cube.AMax)] + - moments[GetPaletteIndex(position, cube.GMax, cube.BMax, cube.AMin)] + - moments[GetPaletteIndex(position, cube.GMax, cube.BMin, cube.AMax)] + + moments[GetPaletteIndex(position, cube.GMax, cube.BMin, cube.AMin)] + - moments[GetPaletteIndex(position, cube.GMin, cube.BMax, cube.AMax)] + + moments[GetPaletteIndex(position, cube.GMin, cube.BMax, cube.AMin)] + + moments[GetPaletteIndex(position, cube.GMin, cube.BMin, cube.AMax)] + - moments[GetPaletteIndex(position, cube.GMin, cube.BMin, cube.AMin)], // Green - case 2: - return moments[GetPaletteIndex(cube.RMax, position, cube.BMax, cube.AMax)] - - moments[GetPaletteIndex(cube.RMax, position, cube.BMax, cube.AMin)] - - moments[GetPaletteIndex(cube.RMax, position, cube.BMin, cube.AMax)] - + moments[GetPaletteIndex(cube.RMax, position, cube.BMin, cube.AMin)] - - moments[GetPaletteIndex(cube.RMin, position, cube.BMax, cube.AMax)] - + moments[GetPaletteIndex(cube.RMin, position, cube.BMax, cube.AMin)] - + moments[GetPaletteIndex(cube.RMin, position, cube.BMin, cube.AMax)] - - moments[GetPaletteIndex(cube.RMin, position, cube.BMin, cube.AMin)]; + 2 => moments[GetPaletteIndex(cube.RMax, position, cube.BMax, cube.AMax)] + - moments[GetPaletteIndex(cube.RMax, position, cube.BMax, cube.AMin)] + - moments[GetPaletteIndex(cube.RMax, position, cube.BMin, cube.AMax)] + + moments[GetPaletteIndex(cube.RMax, position, cube.BMin, cube.AMin)] + - moments[GetPaletteIndex(cube.RMin, position, cube.BMax, cube.AMax)] + + moments[GetPaletteIndex(cube.RMin, position, cube.BMax, cube.AMin)] + + moments[GetPaletteIndex(cube.RMin, position, cube.BMin, cube.AMax)] + - moments[GetPaletteIndex(cube.RMin, position, cube.BMin, cube.AMin)], // Blue - case 1: - return moments[GetPaletteIndex(cube.RMax, cube.GMax, position, cube.AMax)] - - moments[GetPaletteIndex(cube.RMax, cube.GMax, position, cube.AMin)] - - moments[GetPaletteIndex(cube.RMax, cube.GMin, position, cube.AMax)] - + moments[GetPaletteIndex(cube.RMax, cube.GMin, position, cube.AMin)] - - moments[GetPaletteIndex(cube.RMin, cube.GMax, position, cube.AMax)] - + moments[GetPaletteIndex(cube.RMin, cube.GMax, position, cube.AMin)] - + moments[GetPaletteIndex(cube.RMin, cube.GMin, position, cube.AMax)] - - moments[GetPaletteIndex(cube.RMin, cube.GMin, position, cube.AMin)]; + 1 => moments[GetPaletteIndex(cube.RMax, cube.GMax, position, cube.AMax)] + - moments[GetPaletteIndex(cube.RMax, cube.GMax, position, cube.AMin)] + - moments[GetPaletteIndex(cube.RMax, cube.GMin, position, cube.AMax)] + + moments[GetPaletteIndex(cube.RMax, cube.GMin, position, cube.AMin)] + - moments[GetPaletteIndex(cube.RMin, cube.GMax, position, cube.AMax)] + + moments[GetPaletteIndex(cube.RMin, cube.GMax, position, cube.AMin)] + + moments[GetPaletteIndex(cube.RMin, cube.GMin, position, cube.AMax)] + - moments[GetPaletteIndex(cube.RMin, cube.GMin, position, cube.AMin)], // Alpha - case 0: - return moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMax, position)] - - moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMin, position)] - - moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMax, position)] - + moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, position)] - - moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMax, position)] - + moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, position)] - + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, position)] - - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, position)]; - - default: - throw new ArgumentOutOfRangeException(nameof(direction)); - } - } + 0 => moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMax, position)] + - moments[GetPaletteIndex(cube.RMax, cube.GMax, cube.BMin, position)] + - moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMax, position)] + + moments[GetPaletteIndex(cube.RMax, cube.GMin, cube.BMin, position)] + - moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMax, position)] + + moments[GetPaletteIndex(cube.RMin, cube.GMax, cube.BMin, position)] + + moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMax, position)] + - moments[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, position)], + _ => throw new ArgumentOutOfRangeException(nameof(direction)), + }; /// /// Builds a 3-D color histogram of counts, r/g/b, c^2. @@ -498,7 +489,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization - momentSpan[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMax)] + momentSpan[GetPaletteIndex(cube.RMin, cube.GMin, cube.BMin, cube.AMin)]; - var vector = new Vector4(volume.R, volume.G, volume.B, volume.A); + Vector4 vector = new(volume.R, volume.G, volume.B, volume.A); return variance.Moment2 - (Vector4.Dot(vector, vector) / volume.Weight); } @@ -533,7 +524,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization continue; } - var vector = new Vector4(half.R, half.G, half.B, half.A); + Vector4 vector = new(half.R, half.G, half.B, half.A); float temp = Vector4.Dot(vector, vector) / half.Weight; half = whole - half; @@ -816,7 +807,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Quantization x.A += y.A; x.Weight++; - var vector = new Vector4(y.R, y.G, y.B, y.A); + Vector4 vector = new(y.R, y.G, y.B, y.A); x.Moment2 += Vector4.Dot(vector, vector); return x; diff --git a/src/ImageSharp/Processing/Processors/Transforms/Linear/FlipProcessor{TPixel}.cs b/src/ImageSharp/Processing/Processors/Transforms/Linear/FlipProcessor{TPixel}.cs index 7dc8b7365e..3f4e18b8c7 100644 --- a/src/ImageSharp/Processing/Processors/Transforms/Linear/FlipProcessor{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Transforms/Linear/FlipProcessor{TPixel}.cs @@ -27,10 +27,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms /// The source for the current processor instance. /// The source area to process for the current processor instance. public FlipProcessor(Configuration configuration, FlipProcessor definition, Image source, Rectangle sourceRectangle) - : base(configuration, source, sourceRectangle) - { - this.definition = definition; - } + : base(configuration, source, sourceRectangle) => this.definition = definition; /// protected override void OnFrameApply(ImageFrame source) @@ -39,10 +36,10 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms { // No default needed as we have already set the pixels. case FlipMode.Vertical: - this.FlipX(source.PixelBuffer, this.Configuration); + FlipX(source.PixelBuffer, this.Configuration); break; case FlipMode.Horizontal: - this.FlipY(source, this.Configuration); + FlipY(source, this.Configuration); break; } } @@ -52,7 +49,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms /// /// The source image to apply the process to. /// The configuration. - private void FlipX(Buffer2D source, Configuration configuration) + private static void FlipX(Buffer2D source, Configuration configuration) { int height = source.Height; using IMemoryOwner tempBuffer = configuration.MemoryAllocator.Allocate(source.Width); @@ -74,7 +71,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms /// /// The source image to apply the process to. /// The configuration. - private void FlipY(ImageFrame source, Configuration configuration) + private static void FlipY(ImageFrame source, Configuration configuration) { var operation = new RowOperation(source.PixelBuffer); ParallelRowIterator.IterateRows( diff --git a/src/ImageSharp/Processing/Processors/Transforms/Linear/RotateProcessor{TPixel}.cs b/src/ImageSharp/Processing/Processors/Transforms/Linear/RotateProcessor{TPixel}.cs index 8e26675d86..8f6ba28963 100644 --- a/src/ImageSharp/Processing/Processors/Transforms/Linear/RotateProcessor{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Transforms/Linear/RotateProcessor{TPixel}.cs @@ -104,19 +104,19 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms if (MathF.Abs(degrees - 90) < Constants.Epsilon) { - this.Rotate90(source, destination, configuration); + Rotate90(source, destination, configuration); return true; } if (MathF.Abs(degrees - 180) < Constants.Epsilon) { - this.Rotate180(source, destination, configuration); + Rotate180(source, destination, configuration); return true; } if (MathF.Abs(degrees - 270) < Constants.Epsilon) { - this.Rotate270(source, destination, configuration); + Rotate270(source, destination, configuration); return true; } @@ -129,7 +129,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms /// The source image. /// The destination image. /// The configuration. - private void Rotate180(ImageFrame source, ImageFrame destination, Configuration configuration) + private static void Rotate180(ImageFrame source, ImageFrame destination, Configuration configuration) { var operation = new Rotate180RowOperation(source.Width, source.Height, source.PixelBuffer, destination.PixelBuffer); ParallelRowIterator.IterateRows( @@ -144,7 +144,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms /// The source image. /// The destination image. /// The configuration. - private void Rotate270(ImageFrame source, ImageFrame destination, Configuration configuration) + private static void Rotate270(ImageFrame source, ImageFrame destination, Configuration configuration) { var operation = new Rotate270RowIntervalOperation(destination.Bounds(), source.Width, source.Height, source.PixelBuffer, destination.PixelBuffer); ParallelRowIterator.IterateRowIntervals( @@ -159,7 +159,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms /// The source image. /// The destination image. /// The configuration. - private void Rotate90(ImageFrame source, ImageFrame destination, Configuration configuration) + private static void Rotate90(ImageFrame source, ImageFrame destination, Configuration configuration) { var operation = new Rotate90RowOperation(destination.Bounds(), source.Width, source.Height, source.PixelBuffer, destination.PixelBuffer); ParallelRowIterator.IterateRows( diff --git a/src/ImageSharp/Processing/Processors/Transforms/Resamplers/CubicResampler.cs b/src/ImageSharp/Processing/Processors/Transforms/Resamplers/CubicResampler.cs index 4a87c1ea99..53dfb466f8 100644 --- a/src/ImageSharp/Processing/Processors/Transforms/Resamplers/CubicResampler.cs +++ b/src/ImageSharp/Processing/Processors/Transforms/Resamplers/CubicResampler.cs @@ -23,31 +23,31 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms /// This filter produces a reasonably sharp edge, but without a the pronounced gradient change on large /// scale image enlargements that a 'Lagrange' filter can produce. /// - public static CubicResampler CatmullRom = new CubicResampler(2, 0, .5F); + public static readonly CubicResampler CatmullRom = new(2, 0, .5F); /// /// The Hermite filter is type of smoothed triangular interpolation Filter, /// This filter rounds off strong edges while preserving flat 'color levels' in the original image. /// - public static CubicResampler Hermite = new CubicResampler(2, 0, 0); + public static readonly CubicResampler Hermite = new(2, 0, 0); /// /// The function implements the Mitchell-Netravali algorithm as described on /// Wikipedia /// - public static CubicResampler MitchellNetravali = new CubicResampler(2, .3333333F, .3333333F); + public static readonly CubicResampler MitchellNetravali = new(2, .3333333F, .3333333F); /// /// The function implements the Robidoux algorithm. /// /// - public static CubicResampler Robidoux = new CubicResampler(2, .37821575509399867F, .31089212245300067F); + public static readonly CubicResampler Robidoux = new(2, .37821575509399867F, .31089212245300067F); /// /// The function implements the Robidoux Sharp algorithm. /// /// - public static CubicResampler RobidouxSharp = new CubicResampler(2, .2620145123990142F, .3689927438004929F); + public static readonly CubicResampler RobidouxSharp = new(2, .2620145123990142F, .3689927438004929F); /// /// The function implements the spline algorithm. @@ -57,7 +57,7 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms /// The function implements the Robidoux Sharp algorithm. /// /// - public static CubicResampler Spline = new CubicResampler(2, 1, 0); + public static readonly CubicResampler Spline = new(2, 1, 0); /// /// Initializes a new instance of the struct. diff --git a/src/ImageSharp/Processing/Processors/Transforms/Resamplers/LanczosResampler.cs b/src/ImageSharp/Processing/Processors/Transforms/Resamplers/LanczosResampler.cs index 23d8efa624..30bc5b5def 100644 --- a/src/ImageSharp/Processing/Processors/Transforms/Resamplers/LanczosResampler.cs +++ b/src/ImageSharp/Processing/Processors/Transforms/Resamplers/LanczosResampler.cs @@ -15,22 +15,22 @@ namespace SixLabors.ImageSharp.Processing.Processors.Transforms /// /// Implements the Lanczos kernel algorithm with a radius of 2. /// - public static LanczosResampler Lanczos2 = new LanczosResampler(2); + public static readonly LanczosResampler Lanczos2 = new(2); /// /// Implements the Lanczos kernel algorithm with a radius of 3. /// - public static LanczosResampler Lanczos3 = new LanczosResampler(3); + public static readonly LanczosResampler Lanczos3 = new(3); /// /// Implements the Lanczos kernel algorithm with a radius of 5. /// - public static LanczosResampler Lanczos5 = new LanczosResampler(5); + public static readonly LanczosResampler Lanczos5 = new(5); /// /// Implements the Lanczos kernel algorithm with a radius of 8. /// - public static LanczosResampler Lanczos8 = new LanczosResampler(8); + public static readonly LanczosResampler Lanczos8 = new(8); /// /// Initializes a new instance of the struct. diff --git a/src/ImageSharp/Processing/ResizeOptions.cs b/src/ImageSharp/Processing/ResizeOptions.cs index 3c31c7628f..c7b862c1a5 100644 --- a/src/ImageSharp/Processing/ResizeOptions.cs +++ b/src/ImageSharp/Processing/ResizeOptions.cs @@ -39,7 +39,7 @@ namespace SixLabors.ImageSharp.Processing /// Gets or sets a value indicating whether to compress /// or expand individual pixel colors the value on processing. /// - public bool Compand { get; set; } = false; + public bool Compand { get; set; } /// /// Gets or sets the target rectangle to resize into. diff --git a/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs b/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs index 063ba63cd6..6ecb606f53 100644 --- a/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs +++ b/tests/ImageSharp.Tests/Advanced/AdvancedImageExtensionsTests.cs @@ -4,7 +4,6 @@ using System; using System.Linq; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; @@ -50,7 +49,7 @@ namespace SixLabors.ImageSharp.Tests.Advanced image.Mutate(c => c.Resize(8, 8)); Assert.False(memoryGroup.IsValid); - Assert.ThrowsAny(() => _ = memoryGroup.First()); + Assert.ThrowsAny(() => _ = memoryGroup[0]); Assert.ThrowsAny(() => _ = memory.Span); } diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieXyyConversionTest.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieXyyConversionTest.cs index 10d18d63c6..0cd258bd9e 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieXyyConversionTest.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CieXyzAndCieXyyConversionTest.cs @@ -36,8 +36,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new CieXyz[5]; // Act - var actual = Converter.ToCieXyz(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToCieXyz(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); @@ -64,8 +64,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new CieXyy[5]; // Act - var actual = Converter.ToCieXyy(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToCieXyy(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndHslConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndHslConversionTests.cs index 9e08d572fa..095b5e1255 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndHslConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndHslConversionTests.cs @@ -34,8 +34,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new Hsl[5]; // Act - var actual = Converter.ToHsl(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToHsl(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); @@ -64,8 +64,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new Cmyk[5]; // Act - var actual = Converter.ToCmyk(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToCmyk(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndHsvConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndHsvConversionTests.cs index 44de7383a9..770840e9be 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndHsvConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndHsvConversionTests.cs @@ -34,8 +34,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new Hsv[5]; // Act - var actual = Converter.ToHsv(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToHsv(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); @@ -64,8 +64,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new Cmyk[5]; // Act - var actual = Converter.ToCmyk(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToCmyk(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndYCbCrConversionTests.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndYCbCrConversionTests.cs index 9c156b18d8..a67af332d7 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndYCbCrConversionTests.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/CmykAndYCbCrConversionTests.cs @@ -34,8 +34,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new YCbCr[5]; // Act - var actual = Converter.ToYCbCr(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToYCbCr(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndCmykConversionTest.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndCmykConversionTest.cs index 3f23866372..04abcf9788 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndCmykConversionTest.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndCmykConversionTest.cs @@ -40,8 +40,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new Rgb[5]; // Act - var actual = Converter.ToRgb(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToRgb(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(Rgb.DefaultWorkingSpace, actual.WorkingSpace, ColorSpaceComparer); @@ -72,8 +72,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new Cmyk[5]; // Act - var actual = Converter.ToCmyk(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToCmyk(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHslConversionTest.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHslConversionTest.cs index a5fd9ca770..f1075f8666 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHslConversionTest.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHslConversionTest.cs @@ -43,8 +43,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new Rgb[5]; // Act - var actual = Converter.ToRgb(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToRgb(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(Rgb.DefaultWorkingSpace, actual.WorkingSpace, ColorSpaceComparer); @@ -78,8 +78,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new Hsl[5]; // Act - var actual = Converter.ToHsl(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToHsl(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHsvConversionTest.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHsvConversionTest.cs index e7e95e7922..2d801b5405 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHsvConversionTest.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndHsvConversionTest.cs @@ -42,8 +42,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new Rgb[5]; // Act - var actual = Converter.ToRgb(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToRgb(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(Rgb.DefaultWorkingSpace, actual.WorkingSpace, ColorSpaceComparer); @@ -76,8 +76,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new Hsv[5]; // Act - var actual = Converter.ToHsv(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToHsv(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); diff --git a/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndYCbCrConversionTest.cs b/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndYCbCrConversionTest.cs index 297b4ad138..0b4193c1ae 100644 --- a/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndYCbCrConversionTest.cs +++ b/tests/ImageSharp.Tests/Colorspaces/Conversion/RgbAndYCbCrConversionTest.cs @@ -71,8 +71,8 @@ namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion Span actualSpan = new YCbCr[5]; // Act - var actual = Converter.ToYCbCr(input); - Converter.Convert(inputSpan, actualSpan); + var actual = ColorSpaceConverter.ToYCbCr(input); + ColorSpaceConverter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); diff --git a/tests/ImageSharp.Tests/Formats/Jpg/JpegColorConverterTests.cs b/tests/ImageSharp.Tests/Formats/Jpg/JpegColorConverterTests.cs index c6f74869e2..deeff0992a 100644 --- a/tests/ImageSharp.Tests/Formats/Jpg/JpegColorConverterTests.cs +++ b/tests/ImageSharp.Tests/Formats/Jpg/JpegColorConverterTests.cs @@ -39,7 +39,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg public void GetConverterThrowsExceptionOnInvalidColorSpace() { var invalidColorSpace = (JpegColorSpace)(-1); - Assert.Throws(() => JpegColorConverterBase.GetConverter(invalidColorSpace, 8)); + Assert.Throws(() => JpegColorConverterBase.GetConverter(invalidColorSpace, 8)); } [Fact] @@ -47,7 +47,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Jpg { // Valid precisions: 8 & 12 bit int invalidPrecision = 9; - Assert.Throws(() => JpegColorConverterBase.GetConverter(JpegColorSpace.YCbCr, invalidPrecision)); + Assert.Throws(() => JpegColorConverterBase.GetConverter(JpegColorSpace.YCbCr, invalidPrecision)); } [Theory] diff --git a/tests/ImageSharp.Tests/Formats/Tiff/BigTiffMetadataTests.cs b/tests/ImageSharp.Tests/Formats/Tiff/BigTiffMetadataTests.cs index bb26d182b7..9ce45d3f36 100644 --- a/tests/ImageSharp.Tests/Formats/Tiff/BigTiffMetadataTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tiff/BigTiffMetadataTests.cs @@ -245,7 +245,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tiff private static void WriteLong8(TiffStreamWriter writer, byte[] buffer, ulong value) { - if (writer.IsLittleEndian) + if (TiffStreamWriter.IsLittleEndian) { BinaryPrimitives.WriteUInt64LittleEndian(buffer, value); } diff --git a/tests/ImageSharp.Tests/Formats/Tiff/TiffEncoderHeaderTests.cs b/tests/ImageSharp.Tests/Formats/Tiff/TiffEncoderHeaderTests.cs index 6874019a0d..2d594319e6 100644 --- a/tests/ImageSharp.Tests/Formats/Tiff/TiffEncoderHeaderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tiff/TiffEncoderHeaderTests.cs @@ -25,7 +25,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tiff using (var writer = new TiffStreamWriter(stream)) { - long firstIfdMarker = encoder.WriteHeader(writer); + long firstIfdMarker = TiffEncoderCore.WriteHeader(writer); } Assert.Equal(new byte[] { 0x49, 0x49, 42, 0, 0x00, 0x00, 0x00, 0x00 }, stream.ToArray()); @@ -39,7 +39,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tiff using (var writer = new TiffStreamWriter(stream)) { - long firstIfdMarker = encoder.WriteHeader(writer); + long firstIfdMarker = TiffEncoderCore.WriteHeader(writer); Assert.Equal(4, firstIfdMarker); } } diff --git a/tests/ImageSharp.Tests/Formats/Tiff/Utils/TiffWriterTests.cs b/tests/ImageSharp.Tests/Formats/Tiff/Utils/TiffWriterTests.cs index cc32779819..253381985e 100644 --- a/tests/ImageSharp.Tests/Formats/Tiff/Utils/TiffWriterTests.cs +++ b/tests/ImageSharp.Tests/Formats/Tiff/Utils/TiffWriterTests.cs @@ -16,7 +16,7 @@ namespace SixLabors.ImageSharp.Tests.Formats.Tiff.Utils { using var stream = new MemoryStream(); using var writer = new TiffStreamWriter(stream); - Assert.True(writer.IsLittleEndian); + Assert.True(TiffStreamWriter.IsLittleEndian); } [Theory] diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccReaderTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccReaderTests.cs index a21a4f0493..184a6c42e9 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccReaderTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccReaderTests.cs @@ -14,7 +14,7 @@ namespace SixLabors.ImageSharp.Tests.Metadata.Profiles.Icc { IccReader reader = this.CreateReader(); - IccProfile output = reader.Read(IccTestDataProfiles.Header_Random_Array); + IccProfile output = IccReader.Read(IccTestDataProfiles.Header_Random_Array); Assert.Equal(0, output.Entries.Length); Assert.NotNull(output.Header); @@ -45,7 +45,7 @@ namespace SixLabors.ImageSharp.Tests.Metadata.Profiles.Icc { IccReader reader = this.CreateReader(); - IccProfile output = reader.Read(IccTestDataProfiles.Profile_Random_Array); + IccProfile output = IccReader.Read(IccTestDataProfiles.Profile_Random_Array); Assert.Equal(2, output.Entries.Length); Assert.True(ReferenceEquals(output.Entries[0], output.Entries[1])); diff --git a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccWriterTests.cs b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccWriterTests.cs index 7aa587a327..039d126630 100644 --- a/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccWriterTests.cs +++ b/tests/ImageSharp.Tests/Metadata/Profiles/ICC/IccWriterTests.cs @@ -18,7 +18,7 @@ namespace SixLabors.ImageSharp.Tests.Metadata.Profiles.Icc { Header = IccTestDataProfiles.Header_Random_Write }; - byte[] output = writer.Write(profile); + byte[] output = IccWriter.Write(profile); Assert.Equal(IccTestDataProfiles.Header_Random_Array, output); } @@ -28,7 +28,7 @@ namespace SixLabors.ImageSharp.Tests.Metadata.Profiles.Icc { IccWriter writer = this.CreateWriter(); - byte[] output = writer.Write(IccTestDataProfiles.Profile_Random_Val); + byte[] output = IccWriter.Write(IccTestDataProfiles.Profile_Random_Val); Assert.Equal(IccTestDataProfiles.Profile_Random_Array, output); }