如何将 ushort 16 位数组转换为图像 C#

How can I convert an ushort 16 bit array to an image C#

我有一个 16 位 ushort 数组,其值范围为 0 到 65535,我想将其转换为灰度图像以保存。我尝试做的是将值写入图像数据类型,然后将图像转换为位图,但是一旦我将其放入位图数据类型,它就会转换为 8 位数据。

using (Image<Gray, ushort> DisplayImage2 = new Image<Gray, ushort>(Width, Height))
{
    int Counter = 0;
    for (int i = 0; i < Height; i++)
    {
        for (int j = 0; j < Width; j++)
        {
            DisplayImage.Data[i, j, 0] = ushortArray[Counter];
            Counter++;
        }
    }
    Bitmap bitt = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);
    bitt = DisplayImage2.ToBitmap();
    bitt.Save(SaveDirectory, System.Drawing.Imaging.ImageFormat.Tiff);)
}

一旦将图像放入位图 bitt,它就会更改为 8 位,有没有办法做到这一点?谢谢

改编自关于如何将 Format16bppGrayScale 位图存储为 TIFF 的 linked answer,但没有先创建实际的位图。这需要一些您通常不会添加为引用的 .NET dll,即 PresentationCore 和 WindowsBase。

构造 TIFF 编码器可以编码的 BitmapFrame 所必需的 BitmapSource 可以直接从数组创建,因此:

var bitmapSrc = BitmapSource.Create(Width, Height, 96, 96,
                                    PixelFormats.Gray16, null, rawData, Width * 2);
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.Zip;
encoder.Frames.Add(BitmapFrame.Create(bitmapSrc));
encoder.Save(outputStream);

当我尝试这个时,文件似乎是一个真正的 16 位图像。