Search code examples
c#.netbitmap

Convert 1d array to grayscale bitmap C#


I have 1d array which contains the pixel values in range [50,600]. I need to create a bitmap and save image as gray scale.

Below code I tried but my images are blue in color, my expectation in that image should be gray.

            var bitmap = new Bitmap(xL, yL, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);
            int count = 0;
            for (y = 0; y < xL; y++)
            {
                for (x = 0; x < yL; x++)
                {
                    bitmap.SetPixel(x, y, System.Drawing.Color.FromArgb((int) arr[count]));
                    count++;
                }
            }
            bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);

As the values are not 8 bits so I was not using System.Drawing.Color.FromArgb(val,val,val) as it was giving exception "value should be greater than or equal to 0 and less 256".

How can I create gray scale image if my array values lies in range [50,600].

Any help would be greatly appreciated. Thanks.


Solution

  • You need to do the color conversion manually. Since you say that the values range from [50...600], I'm assuming your array arr is of type short[].

    int value = ((arr[count] - 50) * 255) / 550;
    value = Math.Clamp(value, 0, 255);
    Color gray = Color.FromArgb(value, value, value);
    

    That should give you the gray values you're looking for.