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

£可爱£侵袭症+ 提交于 2020-01-03 01:10:52

问题


I'm building a small app using C#/WPF.

The application receives (from an unmanaged C++ library) a byte array (byte[]) from a bitmap source

In my WPF window, I have an (System.windows.Controls.Image) image which I will use to display the bitmap.

In the code behind (C#) I need to able to take that byte array, create BitmapSource /ImageSource and assign the source for my image control.

// 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)
{
    ??????????
}

I've been working on this for a bit here and haven't been able to figure this out. I've tried several solutions that I've found by goolging around. To date, I haven't been able to figure this out.

I've tried:

1) Creating a BitmapSource

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

That through a runtime exception saying buffer was too small Buffer size is not sufficient

2) I tried using a memory stream:

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;
}

This code through an exception on the EndInit() call. "No imaging component suitableto complete this operation was found."

SOS! I've spent a couple of days on this one and am clearly stuck. Any help/ideas/direction would be greatly appreciated.

Thanks, JohnB


回答1:


Your stride calculation is wrong. It is the number of full bytes per scan line, and should therefore be calculated like this:

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

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

Of course you also have to make sure that you use the correct image size, i.e. that the width and height values actually correspond with the data in imageBuffer.



来源:https://stackoverflow.com/questions/29440576/how-do-i-set-a-wpf-images-source-to-a-bytearray-in-c-sharp-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!