I need to be able to convert 8-bit or 16-bit grayscale pixel data into a file format that the .NET framework can support.
The data I have available is the width, height, orientation (bottom-left) and the pixel format as 4096 shades of gray (12-bit resolution) packed in 2 bytes per pixel.
So for example each pixel ranges from 0 to 4096, and each pixel is 2 bytes.
I have already tried using PixelFormat.Format16bppGrayScale with the Bitmap constructor, and it throws a GDI+ exception. Everything I have read says that this format is not supported and that MSDN is wrong.
I want to convert this pixel buffer into a .NET Bitmap format (such as Format32bppArgb) with as little image quality loss as possible.
Anyone know how?
Best Answer
See the example below, which precomputes a lookup table (LUT) and uses that to convert each pixel. This version covers your 12-bit case; for 8-bit the code is very similar, but it is difficult to generalize across pixel formats.
A conversion from 12-bit GS to effectively 8-bit GS will lose data. However, you can adjust the LUT table to focus on a smaller range of input values with better contrast (ex. DICOM Window Center/Window Width).