Skip to content

Commit

Permalink
Merge pull request #286 from drewnoakes/png-chunk-efficiency
Browse files Browse the repository at this point in the history
Reduce allocation when reading PNG chunks
  • Loading branch information
drewnoakes committed May 7, 2021
2 parents 7f52477 + a131ad5 commit cdf9427
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions MetadataExtractor/Formats/Png/PngChunkReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ public IEnumerable<PngChunk> Extract(SequentialReader reader, ICollection<PngChu
// Miscellaneous information: bKGD, hIST, pHYs, sPLT
// Time information: tIME
//
// CHUNK READING
//
// Only chunk data for types specified in desiredChunkTypes is extracted.
// For empty chunk type list NO data is copied from source stream.
// For null chunk type list ALL data is copied from source stream.
//

// network byte order
reader = reader.WithByteOrder(isMotorolaByteOrder: true);
Expand All @@ -68,7 +74,17 @@ public IEnumerable<PngChunk> Extract(SequentialReader reader, ICollection<PngChu
throw new PngProcessingException("PNG chunk length exceeds maximum");
var chunkType = new PngChunkType(reader.GetBytes(4));
var willStoreChunk = desiredChunkTypes == null || desiredChunkTypes.Contains(chunkType);
var chunkData = reader.GetBytes(chunkDataLength);

byte[]? chunkData;
if (willStoreChunk)
{
chunkData = reader.GetBytes(chunkDataLength);
}
else
{
chunkData = null;
reader.Skip(chunkDataLength);
}

// Skip the CRC bytes at the end of the chunk
// TODO consider verifying the CRC value to determine if we're processing bad data
Expand All @@ -85,7 +101,8 @@ public IEnumerable<PngChunk> Extract(SequentialReader reader, ICollection<PngChu
if (chunkType.Equals(PngChunkType.IEND))
seenImageTrailer = true;

if (willStoreChunk)
// chunkData will be null if we aren't interested in this chunk
if (chunkData is not null)
chunks.Add(new PngChunk(chunkType, chunkData));

seenChunkTypes.Add(chunkType);
Expand Down

0 comments on commit cdf9427

Please sign in to comment.