From b48dbc5087de9bd98dc8ed0f478550e22d4e1ff9 Mon Sep 17 00:00:00 2001 From: antonfirsov Date: Sat, 2 Sep 2023 00:00:47 +0200 Subject: [PATCH] if transparencyIndex is outside the palette, ignore it --- .../Quantization/EuclideanPixelMap{TPixel}.cs | 31 +++++-------------- 1 file changed, 8 insertions(+), 23 deletions(-) diff --git a/src/ImageSharp/Processing/Processors/Quantization/EuclideanPixelMap{TPixel}.cs b/src/ImageSharp/Processing/Processors/Quantization/EuclideanPixelMap{TPixel}.cs index e767ac4f7..f75664903 100644 --- a/src/ImageSharp/Processing/Processors/Quantization/EuclideanPixelMap{TPixel}.cs +++ b/src/ImageSharp/Processing/Processors/Quantization/EuclideanPixelMap{TPixel}.cs @@ -53,21 +53,16 @@ internal sealed class EuclideanPixelMap : IDisposable this.rgbaPalette = new Rgba32[palette.Length]; this.cache = new ColorDistanceCache(configuration.MemoryAllocator); PixelOperations.Instance.ToRgba32(configuration, this.Palette.Span, this.rgbaPalette); - this.transparentIndex = transparentIndex; + + // If the provided transparentIndex is outside of the palette, silently ignore it. + this.transparentIndex = transparentIndex < this.Palette.Length ? transparentIndex : -1; } /// /// Gets the color palette of this . /// The palette memory is owned by the palette source that created it. /// - public ReadOnlyMemory Palette - { - [MethodImpl(InliningOptions.ShortMethod)] - get; - - [MethodImpl(InliningOptions.ShortMethod)] - private set; - } + public ReadOnlyMemory Palette { get; private set; } /// /// Returns the closest color in the palette and the index of that pixel. @@ -106,10 +101,10 @@ internal sealed class EuclideanPixelMap : IDisposable } /// - /// Allows setting the transparent index after construction. + /// Allows setting the transparent index after construction. If the provided transparentIndex is outside of the palette, silently ignore it. /// /// An explicit index at which to match transparent pixels. - public void SetTransparentIndex(int index) => this.transparentIndex = index; + public void SetTransparentIndex(int index) => this.transparentIndex = index < this.Palette.Length ? index : -1; [MethodImpl(InliningOptions.ShortMethod)] private int GetClosestColorSlow(Rgba32 rgba, ref TPixel paletteRef, out TPixel match) @@ -122,19 +117,9 @@ internal sealed class EuclideanPixelMap : IDisposable { // We have explicit instructions. No need to search. index = this.transparentIndex; + DebugGuard.MustBeLessThan(index, this.Palette.Length, nameof(index)); this.cache.Add(rgba, (byte)index); - - if (index >= 0 && index < this.Palette.Length) - { - match = Unsafe.Add(ref paletteRef, (uint)index); - } - else - { - Unsafe.SkipInit(out TPixel pixel); - pixel.FromScaledVector4(Vector4.Zero); - match = pixel; - } - + match = Unsafe.Add(ref paletteRef, (uint)index); return index; }