Search code examples
c#wpfbitmapbitmapimageimagesource

Create a BitmapImage from ushort[]


Is it possible to create a BitmapImage from a ushort array? and if so how?

At the minute I'm creating a Bitmap, converting it to a Bitmap array and displaying it, but this is too slow, I need to continuously update the image (live video feed), while each frame is being created the UI studders, this is making my app very slow when video is running. So I need to get my ushort[] into a BitmapImage as fast as possible

Thanks, Eamonn


Solution

  • Assuming you're working with values between 0 and 255 you could cast it into an array of bytes and then load it into a MemoryStream:

    // Please note that with values higher than 255 the program will throw an exception
    checked
    {
        ushort[] values = { 200, 100, 30/*, 256*/ };
        var bytes = (from value in values
                     select (byte)value).ToArray();
    
        // Taken from: http://stackoverflow.com/questions/5346727/wpf-convert-memory-stream-to-bitmapimage
        using (var stream = new MemoryStream(data))
        {
            var bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.EndInit();
            bitmap.Freeze();
        }
    }