-
Context: I am a contributor on https://github.com/fo-dicom/fo-dicom where we work with raw 16-bit image data. Thanks to a previous discussion here (#1253) I found that I can load the raw pixel data using Now my question is: after mutations, how do I save the raw pixel data back to a Stream. I'm looking for a "RawEncoder" or something similar. I tried reading the documentation and googling for people with a similar issue, but nothing came up. Sorry if I missed it! Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hi @amoerie We were just discussing something similar yesterday actually.
The safest way to do this is currently is. using var ms = new MemoryStream();
using var image = Image<L16>.Load(pixelBytes, _pixelData.Width, _pixelData.Height);
for (int y = 0; i < image.Height; y++)
{
ms.Write(image.GetPixelRowSpan(y));
} |
Beta Was this translation helpful? Give feedback.
-
Thanks for the quick reply! I must apologize, I did find some documentation after all that was helpful, this page contained some helpful pointers that I missed during my initial search: https://docs.sixlabors.com/articles/imagesharp/pixelbuffers.html I came up with something very similar to your suggestion @JimBobSquarePants : P.S. I think your suggestion still requires to convert the Span of TPixel to Span of byte using MemoryMarshal before being able to write to a stream, unless I am mistaken. public class RawEncoder: IImageEncoder
{
public void Encode<TPixel>(Image<TPixel> image, Stream stream) where TPixel : unmanaged, IPixel<TPixel>
{
if(image.TryGetSinglePixelSpan(out var singlePixelSpan))
{
stream.Write(MemoryMarshal.AsBytes(singlePixelSpan));
}
else
{
for (int j = 0; j < image.Height; j++)
{
var rowSpan = image.GetPixelRowSpan(j);
stream.Write(MemoryMarshal.AsBytes(rowSpan));
}
}
}
public Task EncodeAsync<TPixel>(Image<TPixel> image, Stream stream, CancellationToken cancellationToken) where TPixel : unmanaged, IPixel<TPixel>
{
if(image.TryGetSinglePixelSpan(out var singlePixelSpan))
{
stream.Write(MemoryMarshal.AsBytes(singlePixelSpan));
}
else
{
for (int j = 0; j < image.Height; j++)
{
var rowSpan = image.GetPixelRowSpan(j);
stream.Write(MemoryMarshal.AsBytes(rowSpan));
}
}
return Task.CompletedTask;
}
} |
Beta Was this translation helpful? Give feedback.
Thanks for the quick reply!
I must apologize, I did find some documentation after all that was helpful, this page contained some helpful pointers that I missed during my initial search: https://docs.sixlabors.com/articles/imagesharp/pixelbuffers.html
I came up with something very similar to your suggestion @JimBobSquarePants :
P.S. I think your suggestion still requires to convert the Span of TPixel to Span of byte using MemoryMarshal before being able to write to a stream, unless I am mistaken.