Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 872
koryakinp Avatar asked Jan 09 '18 21:01

koryakinp


People also ask

How do I create a byte array image?

Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter). Finally, Write the image to using the write() method of the ImageIo class.


1 Answers

You could do it in this way:

var image = Image.Load<Rgba32>(byteArray);
image.Mutate(x => x.Grayscale());
like image 111
Han Zhao Avatar answered Oct 05 '22 03:10

Han Zhao