2015-04-03 72 views
1

我正在使用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

回答

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中的數據對應。

+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

相關問題