Search code examples
c#.net-coreimagesharp

Create an image from byte[] using ImageSharp


I have a byte[] and I want to create a gray-scale image using ImageSharp library.

That is how I am doing it currently:

byte[] arr = MnistReader.ReadTestData(); //this gives me byte[] with 784 pixel values

ImageSharp.Image image = new ImageSharp.Image(28, 28);

for (int i = 0; i < image.Height; i++)
{
    for (int j = 0; j < image.Width; j++)
    {
        int curPixel = j + i * image.Width;
        image.Pixels[curPixel].R = arr[curPixel];
        image.Pixels[curPixel].G = arr[curPixel];
        image.Pixels[curPixel].B = arr[curPixel];
    }
}

I wonder if there is a more elegant way to do it ?


Solution

  • You could do it in this way:

    var image = Image.Load<Rgba32>(byteArray);
    image.Mutate(x => x.Grayscale());