如何在后面的 C# 代码中将 WPF 图像源设置为字节数组?

How do I set a WPF Image's Source to a bytearray in C# code behind?

我正在使用 C#/WPF 构建一个小应用程序。

应用程序从位图源接收(从非托管 C++ 库)字节数组 (byte[])

在我的 WPF window 中,我有一个 (System.windows.Controls.Image) 图像,我将使用它来显示位图。

在后面的代码 (C#) 中,我需要能够获取该字节数组,创建 BitmapSource /ImageSource 并为我的图像控件分配源。

// byte array source from unmanaged librariy
byte[] imageData; 

// Image Control Definition
System.Windows.Controls.Image image = new Image() {width = 100, height = 100 };

// Assign the Image Source
image.Source = ConvertByteArrayToImageSource(imageData);

private BitmapSource ConvertByteArrayToImagesource(byte[] imageData)
{
    ??????????
}

我在这里研究了一段时间,但一直没弄明白。我已经尝试了几种解决方案,这些解决方案是通过四处寻找而找到的。到目前为止,我还没弄明白。

我试过:

1) 创建位图源

var stride = ((width * PixelFormats.Bgr24 +31) ?32) *4);
var imageSrc = BitmapSource.Create(width, height, 96d, 96d, PixelFormats.Bgr24, null, imageData, stride);

通过运行时异常说缓冲区太小 缓冲区大小不足

2) 我尝试使用内存流:

BitmapImage bitmapImage = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
   bitmapImage.BeginInit();
   bitmapImage.CrateOptions = BitmapCreateOptions.PreservePixelFormat;
   bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
   bitmapImage.StreamSource = mem;
   bitmapImage.EndInit();
   return bitmapImage;
}

此代码通过 EndInit() 调用的异常。 "No imaging component suitableto complete this operation was found."

求救!我在这上面花了几天时间,显然卡住了。 任何 help/ideas/direction 将不胜感激。

谢谢, 约翰B

你的步幅计算有误。它是每条扫描线的完整字节数,因此应该这样计算:

var format = PixelFormats.Bgr24;
var stride = (width * format.BitsPerPixel + 7) / 8;

var imageSrc = BitmapSource.Create(
    width, height, 96d, 96d, format, null, imageData, stride);

当然,您还必须确保使用正确的图像尺寸,即 widthheight 值实际上与 imageBuffer 中的数据相对应。