-3

i have tried to convert to grayscale but it is not of 16 bpp how to get a 16 bpp grayscale image using below code.

    for (int y = 0; y < tr.Height; y++)
        {
            for (int x = 0; x < tr.Width; x++)
            {
                //get pixel value
                p = tr.GetPixel(x, y);

                //extract pixel component ARGB
                int a = p.A;
                int r = p.R;
                int g = p.G;
                int b = p.B;

                //find average
                int avg = (r + g + b) / 3;

                //set new pixel value
                tr.SetPixel(x, y, Color.FromArgb(a, avg, avg, avg));
            }
        }

1 Answers1

0

Here you're only changing colors, not changing pixel format. The average you calculate will be between 0 and 255, and then you set each channel in your still-RGBA image to that number. To get more resolution in your calculated averages, you could multiply each channel by 256 before summing. Then the average you calculate will be between 0 and 65535. But you would want to save these values, not to your original Bitmap (which is still in the RGBA format) but to a Bitmap with a PixelFormat of Format16bppGrayScale.

...But I should warn you that this is futile, because somewhere along the way (I forget where, exactly) you will discover that there's essentially no way to save a Bitmap to a truly grayscale format. It'll always come out RGB or indexed. As far as I understand it, this is a limitation of GDI+. For more information, you can cross your fingers that maybe Hans Passant will comment on your question. I'll try to find a link to a question where he explains the problem.

Oh, I should further add that averaging the R, G, and B channels isn't the "correct" way to convert a color to grayscale. See this question for more details.

And I guess I should further note, in case you haven't read it elsewhere, that GetPixel and SetPixel are slow, and for setting a lot of data it's recommended to use LockBits and UnlockBits.

Community
  • 1
  • 1
adv12
  • 8,443
  • 2
  • 24
  • 48