From c512b142f93f675fcbbdcb32efd5635b1c67a842 Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Thu, 12 Mar 2026 10:56:20 +0100 Subject: [PATCH] If alpha length is greater then colorTable, slice length to colorTable length --- src/ImageSharp/Formats/Png/PngDecoderCore.cs | 4 ++-- .../ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/ImageSharp/Formats/Png/PngDecoderCore.cs b/src/ImageSharp/Formats/Png/PngDecoderCore.cs index 0a7a5d359b..8962182679 100644 --- a/src/ImageSharp/Formats/Png/PngDecoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngDecoderCore.cs @@ -1253,10 +1253,10 @@ internal sealed class PngDecoderCore : ImageDecoderCore ReadOnlySpan rgbTable = MemoryMarshal.Cast(palette); Color.FromPixel(rgbTable, colorTable); + // The tRNS chunk must not contain more alpha values than there are palette entries. if (alpha.Length > colorTable.Length) { - throw new InvalidImageContentException( - "The tRNS chunk contains more alpha values than there are palette entries."); + alpha = alpha.Slice(0, colorTable.Length); } if (alpha.Length > 0) diff --git a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs index a53bd1dd5c..03dc040186 100644 --- a/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs +++ b/tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.Chunks.cs @@ -162,7 +162,7 @@ public partial class PngDecoderTests } [Fact] - public void Decode_tRnsChunk_WithAlphaLengthGreaterColorTableLength_ExceptionIsThrown() + public void Decode_tRnsChunk_WithAlphaLengthGreaterColorTableLength_ShouldNotThrowException() { byte[] payload = [137, 80, 78, 71, 13, 10, 26, 10, // PNG signature 0, 0, 0, 13, // chunk length 13 bytes @@ -181,9 +181,7 @@ public partial class PngDecoderTests 120, 156, 99, 96, 0, 0, 0, 2, 0, 1, 72, 175, 164, 113]; // alpha.Length > colorTable.Length using MemoryStream stream = new(payload); - InvalidImageContentException exception = Assert.Throws(() => Image.Load(stream)); - - Assert.Equal("The tRNS chunk contains more alpha values than there are palette entries.", exception.Message); + using Image image = Image.Load(stream); } private static string GetChunkTypeName(uint value)