|
3 | 3 | #nullable disable |
4 | 4 |
|
5 | 5 | using System.Buffers.Binary; |
| 6 | +using System.Text; |
6 | 7 | using SixLabors.ImageSharp.Common.Helpers; |
7 | 8 | using SixLabors.ImageSharp.Formats.Jpeg.Components; |
8 | 9 | using SixLabors.ImageSharp.Formats.Jpeg.Components.Encoder; |
@@ -89,6 +90,9 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken |
89 | 90 | // Write Exif, XMP, ICC and IPTC profiles |
90 | 91 | this.WriteProfiles(metadata, buffer); |
91 | 92 |
|
| 93 | + // Write comments |
| 94 | + this.WriteComment(jpegMetadata); |
| 95 | + |
92 | 96 | // Write the image dimensions. |
93 | 97 | this.WriteStartOfFrame(image.Width, image.Height, frameConfig, buffer); |
94 | 98 |
|
@@ -167,6 +171,47 @@ private void WriteJfifApplicationHeader(ImageMetadata meta, Span<byte> buffer) |
167 | 171 | this.outputStream.Write(buffer, 0, 18); |
168 | 172 | } |
169 | 173 |
|
| 174 | + /// <summary> |
| 175 | + /// Writes comment |
| 176 | + /// </summary> |
| 177 | + /// <param name="metadata">The image metadata.</param> |
| 178 | + private void WriteComment(JpegMetadata metadata) |
| 179 | + { |
| 180 | + if (metadata.Comments is { Count: 0 }) |
| 181 | + { |
| 182 | + return; |
| 183 | + } |
| 184 | + |
| 185 | + // Length (comment strings lengths) + (comments markers with payload sizes) |
| 186 | + int commentsBytes = metadata.Comments.Sum(x => x.Length) + (metadata.Comments.Count * 4); |
| 187 | + int commentStart = 0; |
| 188 | + Span<byte> commentBuffer = stackalloc byte[commentsBytes]; |
| 189 | + |
| 190 | + foreach (Memory<char> comment in metadata.Comments) |
| 191 | + { |
| 192 | + int totalComLength = comment.Length + 4; |
| 193 | + |
| 194 | + Span<byte> commentData = commentBuffer.Slice(commentStart, totalComLength); |
| 195 | + Span<byte> markers = commentData.Slice(0, 2); |
| 196 | + Span<byte> payloadSize = commentData.Slice(2, 2); |
| 197 | + Span<byte> payload = commentData.Slice(4, comment.Length); |
| 198 | + |
| 199 | + // Beginning of comment ff fe |
| 200 | + markers[0] = JpegConstants.Markers.XFF; |
| 201 | + markers[1] = JpegConstants.Markers.COM; |
| 202 | + |
| 203 | + // Write payload size |
| 204 | + BinaryPrimitives.WriteInt16BigEndian(payloadSize, (short)(commentData.Length - 2)); |
| 205 | + |
| 206 | + Encoding.ASCII.GetBytes(comment.Span, payload); |
| 207 | + |
| 208 | + // Indicate begin of next comment in buffer |
| 209 | + commentStart += totalComLength; |
| 210 | + } |
| 211 | + |
| 212 | + this.outputStream.Write(commentBuffer, 0, commentBuffer.Length); |
| 213 | + } |
| 214 | + |
170 | 215 | /// <summary> |
171 | 216 | /// Writes the Define Huffman Table marker and tables. |
172 | 217 | /// </summary> |
|
0 commit comments