-
-
Notifications
You must be signed in to change notification settings - Fork 887
Preserve color profile when encoding PNG images #2110
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
Merged
Merged
Changes from 8 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
1c474c7
Add decoding color profile chunk
brianpopow 9b5d56f
Preserve color profile when encoding png's
brianpopow d645ba4
Add test for ICC profile
brianpopow 35d1473
Use const color profile name
brianpopow cc9c167
Merge branch 'main' into bp/png-iccp
brianpopow 8176d4b
Merge branch 'main' into bp/png-iccp
JimBobSquarePants b025d29
Apply suggestions from code review
brianpopow 2dd3598
Avoid allocation, remove code duplication for decompressing zlib data
brianpopow d43ec49
Use memory allocator for destination buffer for the uncomressed bytes
brianpopow a0e38c8
Use memory stream for uncompressed data instead of a list
brianpopow File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -87,6 +87,11 @@ internal sealed class PngEncoderCore : IImageEncoderInternals, IDisposable | |
| /// </summary> | ||
| private IMemoryOwner<byte> currentScanline; | ||
|
|
||
| /// <summary> | ||
| /// The color profile name. | ||
| /// </summary> | ||
| private const string ColorProfileName = "ICC Profile"; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="PngEncoderCore" /> class. | ||
| /// </summary> | ||
|
|
@@ -134,6 +139,7 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken | |
|
|
||
| this.WriteHeaderChunk(stream); | ||
| this.WriteGammaChunk(stream); | ||
| this.WriteColorProfileChunk(stream, metadata); | ||
| this.WritePaletteChunk(stream, quantized); | ||
| this.WriteTransparencyChunk(stream, pngMetadata); | ||
| this.WritePhysicalChunk(stream, metadata); | ||
|
|
@@ -656,7 +662,7 @@ private void WriteExifChunk(Stream stream, ImageMetadata meta) | |
| } | ||
|
|
||
| /// <summary> | ||
| /// Writes an iTXT chunk, containing the XMP metdata to the stream, if such profile is present in the metadata. | ||
| /// Writes an iTXT chunk, containing the XMP metadata to the stream, if such profile is present in the metadata. | ||
| /// </summary> | ||
| /// <param name="stream">The <see cref="Stream"/> containing image data.</param> | ||
| /// <param name="meta">The image metadata.</param> | ||
|
|
@@ -673,7 +679,7 @@ private void WriteXmpChunk(Stream stream, ImageMetadata meta) | |
| return; | ||
| } | ||
|
|
||
| var xmpData = meta.XmpProfile.Data; | ||
| byte[] xmpData = meta.XmpProfile.Data; | ||
|
|
||
| if (xmpData.Length == 0) | ||
| { | ||
|
|
@@ -687,19 +693,49 @@ private void WriteXmpChunk(Stream stream, ImageMetadata meta) | |
| PngConstants.XmpKeyword.CopyTo(payload); | ||
| int bytesWritten = PngConstants.XmpKeyword.Length; | ||
|
|
||
| // Write the iTxt header (all zeros in this case) | ||
| payload[bytesWritten++] = 0; | ||
| payload[bytesWritten++] = 0; | ||
| payload[bytesWritten++] = 0; | ||
| payload[bytesWritten++] = 0; | ||
| payload[bytesWritten++] = 0; | ||
| // Write the iTxt header (all zeros in this case). | ||
| Span<byte> iTxtHeader = payload.Slice(bytesWritten); | ||
| iTxtHeader[4] = 0; | ||
| iTxtHeader[3] = 0; | ||
| iTxtHeader[2] = 0; | ||
| iTxtHeader[1] = 0; | ||
| iTxtHeader[0] = 0; | ||
| bytesWritten += 5; | ||
|
|
||
| // And the XMP data itself | ||
| // And the XMP data itself. | ||
| xmpData.CopyTo(payload.Slice(bytesWritten)); | ||
| this.WriteChunk(stream, PngChunkType.InternationalText, payload); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Writes the color profile chunk. | ||
| /// </summary> | ||
| /// <param name="stream">The stream to write to.</param> | ||
| /// <param name="metaData">The image meta data.</param> | ||
| private void WriteColorProfileChunk(Stream stream, ImageMetadata metaData) | ||
| { | ||
| if (metaData.IccProfile is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| byte[] iccProfileBytes = metaData.IccProfile.ToByteArray(); | ||
|
|
||
| byte[] compressedData = this.GetZlibCompressedBytes(iccProfileBytes); | ||
| int payloadLength = ColorProfileName.Length + compressedData.Length + 2; | ||
| using (IMemoryOwner<byte> owner = this.memoryAllocator.Allocate<byte>(payloadLength)) | ||
| { | ||
| Span<byte> outputBytes = owner.GetSpan(); | ||
| PngConstants.Encoding.GetBytes(ColorProfileName).CopyTo(outputBytes); | ||
| int bytesWritten = ColorProfileName.Length; | ||
| outputBytes[bytesWritten++] = 0; // Null separator. | ||
| outputBytes[bytesWritten++] = 0; // Compression. | ||
|
Comment on lines
+732
to
+733
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here the above "trick" doesn't make sense, as for slicing there's an argument validation, so we just would exchange one comparison for the bound-check against the argument validation. So no net-win. |
||
| compressedData.CopyTo(outputBytes.Slice(bytesWritten)); | ||
| this.WriteChunk(stream, PngChunkType.EmbeddedColorProfile, outputBytes); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Writes a text chunk to the stream. Can be either a tTXt, iTXt or zTXt chunk, | ||
| /// depending whether the text contains any latin characters or should be compressed. | ||
|
|
@@ -727,13 +763,12 @@ private void WriteTextChunks(Stream stream, PngMetadata meta) | |
| } | ||
| } | ||
|
|
||
| if (hasUnicodeCharacters || (!string.IsNullOrWhiteSpace(textData.LanguageTag) || | ||
| !string.IsNullOrWhiteSpace(textData.TranslatedKeyword))) | ||
| if (hasUnicodeCharacters || (!string.IsNullOrWhiteSpace(textData.LanguageTag) || !string.IsNullOrWhiteSpace(textData.TranslatedKeyword))) | ||
| { | ||
| // Write iTXt chunk. | ||
| byte[] keywordBytes = PngConstants.Encoding.GetBytes(textData.Keyword); | ||
| byte[] textBytes = textData.Value.Length > this.options.TextCompressionThreshold | ||
| ? this.GetCompressedTextBytes(PngConstants.TranslatedEncoding.GetBytes(textData.Value)) | ||
| ? this.GetZlibCompressedBytes(PngConstants.TranslatedEncoding.GetBytes(textData.Value)) | ||
| : PngConstants.TranslatedEncoding.GetBytes(textData.Value); | ||
|
|
||
| byte[] translatedKeyword = PngConstants.TranslatedEncoding.GetBytes(textData.TranslatedKeyword); | ||
|
|
@@ -772,18 +807,17 @@ private void WriteTextChunks(Stream stream, PngMetadata meta) | |
| if (textData.Value.Length > this.options.TextCompressionThreshold) | ||
| { | ||
| // Write zTXt chunk. | ||
| byte[] compressedData = | ||
| this.GetCompressedTextBytes(PngConstants.Encoding.GetBytes(textData.Value)); | ||
| byte[] compressedData = this.GetZlibCompressedBytes(PngConstants.Encoding.GetBytes(textData.Value)); | ||
| int payloadLength = textData.Keyword.Length + compressedData.Length + 2; | ||
| using (IMemoryOwner<byte> owner = this.memoryAllocator.Allocate<byte>(payloadLength)) | ||
| { | ||
| Span<byte> outputBytes = owner.GetSpan(); | ||
| PngConstants.Encoding.GetBytes(textData.Keyword).CopyTo(outputBytes); | ||
| int bytesWritten = textData.Keyword.Length; | ||
| outputBytes[bytesWritten++] = 0; | ||
| outputBytes[bytesWritten++] = 0; | ||
| outputBytes[bytesWritten++] = 0; // Null separator. | ||
| outputBytes[bytesWritten++] = 0; // Compression. | ||
| compressedData.CopyTo(outputBytes.Slice(bytesWritten)); | ||
| this.WriteChunk(stream, PngChunkType.CompressedText, outputBytes.ToArray()); | ||
| this.WriteChunk(stream, PngChunkType.CompressedText, outputBytes); | ||
| } | ||
| } | ||
| else | ||
|
|
@@ -796,9 +830,8 @@ private void WriteTextChunks(Stream stream, PngMetadata meta) | |
| PngConstants.Encoding.GetBytes(textData.Keyword).CopyTo(outputBytes); | ||
| int bytesWritten = textData.Keyword.Length; | ||
| outputBytes[bytesWritten++] = 0; | ||
| PngConstants.Encoding.GetBytes(textData.Value) | ||
| .CopyTo(outputBytes.Slice(bytesWritten)); | ||
| this.WriteChunk(stream, PngChunkType.Text, outputBytes.ToArray()); | ||
| PngConstants.Encoding.GetBytes(textData.Value).CopyTo(outputBytes.Slice(bytesWritten)); | ||
| this.WriteChunk(stream, PngChunkType.Text, outputBytes); | ||
| } | ||
| } | ||
| } | ||
|
|
@@ -808,15 +841,15 @@ private void WriteTextChunks(Stream stream, PngMetadata meta) | |
| /// <summary> | ||
| /// Compresses a given text using Zlib compression. | ||
| /// </summary> | ||
| /// <param name="textBytes">The text bytes to compress.</param> | ||
| /// <returns>The compressed text byte array.</returns> | ||
| private byte[] GetCompressedTextBytes(byte[] textBytes) | ||
| /// <param name="dataBytes">The bytes to compress.</param> | ||
| /// <returns>The compressed byte array.</returns> | ||
| private byte[] GetZlibCompressedBytes(byte[] dataBytes) | ||
| { | ||
| using (var memoryStream = new MemoryStream()) | ||
| { | ||
| using (var deflateStream = new ZlibDeflateStream(this.memoryAllocator, memoryStream, this.options.CompressionLevel)) | ||
| { | ||
| deflateStream.Write(textBytes); | ||
| deflateStream.Write(dataBytes); | ||
| } | ||
|
|
||
| return memoryStream.ToArray(); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we use the memory allocator to to create a bigger buffer to read the uncompressed data into here? using the scratch buffer feels like it could be very inefficient.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, lot's of small allocations. I would use the allocator to allocate a buffer of length
Configuration.StreamProcessingBufferSize.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was thinking about this for a while now, but if we always use the allocator this could be also inefficient, if we have alot of small compressed text string's.
Maybe something like this:
For the the buffer to uncomress into?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's actually this line that concerns me the most. Zlib compression is pretty good and you could end up with a large number of
ToArray()calls. That's why I favour a much larger array and simply slicing it. Pooling is pretty cheap.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I dont see how this
ToArraycall can be avoided, though. We cannot pass a Span toAddRange, see dotnet1530There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe
MemoryStream?Can be used with spans and can expand like a list.
No virt calls as we would work with direct type.
Should be relatively fast as it uses
Buffer.InternalBlockCopyfor big buffers.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@br3aker good idea, that will work: a0e38c8