diff --git a/src/ImageSharp/Formats/Png/PngScanlineProcessor.cs b/src/ImageSharp/Formats/Png/PngScanlineProcessor.cs index 26bc566d65..afb89836c0 100644 --- a/src/ImageSharp/Formats/Png/PngScanlineProcessor.cs +++ b/src/ImageSharp/Formats/Png/PngScanlineProcessor.cs @@ -250,6 +250,7 @@ public static void ProcessPaletteScanline( ref TPixel rowSpanRef = ref MemoryMarshal.GetReference(rowSpan); ReadOnlySpan palettePixels = MemoryMarshal.Cast(palette); ref Rgb24 palettePixelsRef = ref MemoryMarshal.GetReference(palettePixels); + int maxIndex = palettePixels.Length - 1; if (paletteAlpha?.Length > 0) { @@ -260,7 +261,7 @@ public static void ProcessPaletteScanline( for (int x = 0; x < header.Width; x++) { - int index = Unsafe.Add(ref scanlineSpanRef, x); + int index = Numerics.Clamp(Unsafe.Add(ref scanlineSpanRef, x), 0, maxIndex); rgba.Rgb = Unsafe.Add(ref palettePixelsRef, index); rgba.A = paletteAlpha.Length > index ? Unsafe.Add(ref paletteAlphaRef, index) : byte.MaxValue; @@ -272,8 +273,8 @@ public static void ProcessPaletteScanline( { for (int x = 0; x < header.Width; x++) { - int index = Unsafe.Add(ref scanlineSpanRef, x); - Rgb24 rgb = Unsafe.Add(ref palettePixelsRef, index); + uint index = Unsafe.Add(ref scanlineSpanRef, x); + Rgb24 rgb = Unsafe.Add(ref palettePixelsRef, (int)Math.Min(index, maxIndex)); pixel.FromRgb24(rgb); Unsafe.Add(ref rowSpanRef, x) = pixel; diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs index a4fcf63baf..c361b1deb4 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs @@ -526,5 +526,13 @@ static void RunTest(string providerDump, string nonContiguousBuffersStr) "Disco") .Dispose(); } + + [Theory] + [InlineData(TestImages.Png.Bad.Issue2714BadPalette)] + public void Decode_BadPalette(string file) + { + string path = Path.GetFullPath(Path.Combine(TestEnvironment.InputImagesDirectoryFullPath, file)); + using Image image = Image.Load(path); + } } } diff --git a/tests/ImageSharp.Tests/TestImages.cs b/tests/ImageSharp.Tests/TestImages.cs index d287ecb4cf..1ae89c508c 100644 --- a/tests/ImageSharp.Tests/TestImages.cs +++ b/tests/ImageSharp.Tests/TestImages.cs @@ -156,6 +156,8 @@ public static class Bad // Invalid color type. public const string ColorTypeOne = "Png/xc1n0g08.png"; public const string ColorTypeNine = "Png/xc9n2c08.png"; + + public const string Issue2714BadPalette = "Png/issues/Issue_2714.png"; } } diff --git a/tests/Images/Input/Png/issues/Issue_2714.png b/tests/Images/Input/Png/issues/Issue_2714.png new file mode 100644 index 0000000000..9bb231dd9f --- /dev/null +++ b/tests/Images/Input/Png/issues/Issue_2714.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a4b6efc3090dbd70ae9efe97ea817464845263536beea4e80fd7c884dee6c5a +size 128