如何将WPF图像的源设置为C#代码后面的bytearray?

时间:2015-04-03 22:33:30

标签: wpf image bytearray bitmapimage

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

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

在我的WPF窗口中,我有一个(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)创建BitmapSource

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()调用的异常。 "没有找到适合完成此操作的成像组件。"

SOS!我在这个上花了几天时间,显然已经被卡住了。 任何帮助/想法/方向将不胜感激。

谢谢, JohnB

1 个答案:

答案 0 :(得分:3)

你的步幅计算错了。它是每条扫描线的完整字节数,因此应按如下方式计算:

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中的数据相对应。