Skip to content

Commit c059656

Browse files
authored
Merge pull request #2021 from SixLabors/bp/invalidgamma
PNG: Ignore invalid gamma chunks
2 parents 6727d6e + d76c40a commit c059656

File tree

4 files changed

+27
-2
lines changed

4 files changed

+27
-2
lines changed

src/ImageSharp/Formats/Png/PngDecoderCore.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -429,10 +429,17 @@ private void ReadPhysicalChunk(ImageMetadata metadata, ReadOnlySpan<byte> data)
429429
/// <param name="pngMetadata">The metadata to read to.</param>
430430
/// <param name="data">The data containing physical data.</param>
431431
private void ReadGammaChunk(PngMetadata pngMetadata, ReadOnlySpan<byte> data)
432+
{
433+
if (data.Length < 4)
434+
{
435+
// Ignore invalid gamma chunks.
436+
return;
437+
}
432438

433-
// The value is encoded as a 4-byte unsigned integer, representing gamma times 100000.
434439
// For example, a gamma of 1/2.2 would be stored as 45455.
435-
=> pngMetadata.Gamma = BinaryPrimitives.ReadUInt32BigEndian(data) * 1e-5F;
440+
// The value is encoded as a 4-byte unsigned integer, representing gamma times 100000.
441+
pngMetadata.Gamma = BinaryPrimitives.ReadUInt32BigEndian(data) * 1e-5F;
442+
}
436443

437444
/// <summary>
438445
/// Initializes the image and various buffers needed for processing

tests/ImageSharp.Tests/Formats/Png/PngDecoderTests.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,20 @@ public void Decode_MissingPaletteChunk_ThrowsException<TPixel>(TestImageProvider
281281
Assert.Contains("PNG Image does not contain a palette chunk", ex.Message);
282282
}
283283

284+
[Theory]
285+
[WithFile(TestImages.Png.Bad.InvalidGammaChunk, PixelTypes.Rgba32)]
286+
public void Decode_InvalidGammaChunk_Ignored<TPixel>(TestImageProvider<TPixel> provider)
287+
where TPixel : unmanaged, IPixel<TPixel>
288+
{
289+
Exception ex = Record.Exception(
290+
() =>
291+
{
292+
using Image<TPixel> image = provider.GetImage(PngDecoder);
293+
image.DebugSave(provider);
294+
});
295+
Assert.Null(ex);
296+
}
297+
284298
[Theory]
285299
[WithFile(TestImages.Png.Bad.BitDepthZero, PixelTypes.Rgba32)]
286300
[WithFile(TestImages.Png.Bad.BitDepthThree, PixelTypes.Rgba32)]

tests/ImageSharp.Tests/TestImages.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ public static class Bad
129129
public const string CorruptedChunk = "Png/big-corrupted-chunk.png";
130130
public const string MissingPaletteChunk1 = "Png/missing_plte.png";
131131
public const string MissingPaletteChunk2 = "Png/missing_plte_2.png";
132+
public const string InvalidGammaChunk = "Png/length_gama.png";
132133

133134
// Zlib errors.
134135
public const string ZlibOverflow = "Png/zlib-overflow.png";
Lines changed: 3 additions & 0 deletions
Loading

0 commit comments

Comments
 (0)