C# Convert SixLabors.ImageSharp Image<Rgba32> to byte[]

138 Views Asked by At

How do I convert the following SixLabors.ImageSharp code into a byte[]

Image<Rgba32> myImage = new Image<Rgba32>();
byte[] myImageByteArray = ...

Someone suggested on a different post to use the following code:

Rgba32[] finalImageByteArray = finalImage
                        .GetPixelMemoryGroup()
                        .SelectMany(group => group.ToArray())
                        .ToArray();

However, this produces a Rgba32[], not a byte[]

1

There are 1 best solutions below

0
Serg On

Try this:

        var img = new Image<Rgba32>(100, 100);
        var bytes = new byte[img.Height*img.Width*img.PixelType.BitsPerPixel/8];
        img.CopyPixelDataTo(bytes);

Some notes:

  • you need to provide preallocated array. So, the size of the array is calculated based on the image size and size of each pixel (divide by 8 to convert bits count to bytes count)
  • you get a copy, not a pointer to the internal buffer of the image object.