7

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 ?

koryakinp
  • 3,989
  • 6
  • 26
  • 56

1 Answers1

15

You could do it in this way:

var image = Image.Load<Rgba32>(byteArray);
image.Mutate(x => x.Grayscale());
Han Zhao
  • 1,932
  • 7
  • 10