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

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

问题描述:

我正在使用C#/ WPF构建一个小应用程序。如何在后面的C#代码中将WPF图像的源设置为bytearray?

应用程序接收到(从非托管C++库)从位图源

字节数组(字节[])以我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

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

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

+0

::>克莱门斯 - 感谢您的答复。我仍然遇到同样的错误。图像宽度= 640,高度= 480; BitsPerPixel = 24;这给了我一个1920的步幅。byte []数组起源于非托管(库)代码。这与它有什么关系? – JohnB 2015-04-06 16:02:07

+0

::>克莱门斯 - 解决方案是正确的(我们的计算结果都返回1920的跨度)。错误的原因是我在计算原始缓冲区的大小时没有考虑通道数(每个像素)。 Thx,JB – JohnB 2015-04-06 16:41:54

+0

也许,如果我们正确地解释了'((width * PixelFormats.Bgr24 +31)?32)* 4)'。至少它不会编译... – Clemens 2015-04-06 18:32:23