简体   繁体   中英

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

I have a 16 bit ushort array with values ranging from 0 to 65535 which I want to convert into a grayscale Image to save. What I tried doing was write the values into an image data type and then converting the image to a bitmap, but as soon as I put it into the bitmap data type it gets converted to 8 bit data.

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);)
}

As soon as the image gets put into the bitmap bitt it gets changed to 8 bit, is there a way of doing this? Thank you

Adapting from the linked answer on how to store a Format16bppGrayScale bitmap as TIFF, but without creating the actual bitmap first. This requires some .NET dlls that you may not usually add as references, namely PresentationCore and WindowsBase.

The BitmapSource necessary to construct the BitmapFrame that the TIFF encoder can encode can be created straight from an array, so:

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);

When I tried this, the file seemed to be a real 16bit image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM