Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve color profile when encoding PNG images #2110

Merged
merged 10 commits into from
May 12, 2022
Prev Previous commit
Next Next commit
Use memory allocator for destination buffer for the uncomressed bytes
brianpopow committed May 11, 2022
commit d43ec499e3cdfe1e0d100e12c781360471e9bc69
10 changes: 5 additions & 5 deletions src/ImageSharp/Formats/Png/PngDecoderCore.cs
Original file line number Diff line number Diff line change
@@ -1222,24 +1222,24 @@ private unsafe bool TryUncompressZlibData(ReadOnlySpan<byte> compressedData, out
{
fixed (byte* compressedDataBase = compressedData)
{
using (IMemoryOwner<byte> destBuffer = this.memoryAllocator.Allocate<byte>(this.Configuration.StreamProcessingBufferSize))
using (var memoryStream = new UnmanagedMemoryStream(compressedDataBase, compressedData.Length))
using (var bufferedStream = new BufferedReadStream(this.Configuration, memoryStream))
using (var inflateStream = new ZlibInflateStream(bufferedStream))
{
Span<byte> dest = destBuffer.GetSpan();
if (!inflateStream.AllocateNewBytes(compressedData.Length, false))
{
uncompressedBytesArray = Array.Empty<byte>();
return false;
}

var uncompressedBytes = new List<byte>(compressedData.Length);

// Note: this uses a buffer which is only 4 bytes long to read the stream, maybe allocating a larger buffer makes sense here.
int bytesRead = inflateStream.CompressedStream.Read(this.buffer, 0, this.buffer.Length);
int bytesRead = inflateStream.CompressedStream.Read(dest, 0, dest.Length);
while (bytesRead != 0)
{
uncompressedBytes.AddRange(this.buffer.AsSpan(0, bytesRead).ToArray());
bytesRead = inflateStream.CompressedStream.Read(this.buffer, 0, this.buffer.Length);
uncompressedBytes.AddRange(dest.Slice(0, bytesRead).ToArray());
bytesRead = inflateStream.CompressedStream.Read(dest, 0, dest.Length);
}

uncompressedBytesArray = uncompressedBytes.ToArray();