tags:

views:

96

answers:

1

I have a high speed camera that I am displaying in a WPF control. The camera's SDK provides me with an array of bytes representing the image data. I'm looking for the most efficient way to bind to these images on a Canvas control. These images are displayed side-by-side from a collection capped at 20 images.

My current method does work exactly the way I want it to, but I feel like there are too many unnecessary conversions.

I first convert my byte array to a Bitmap like so:

//note dataAdress is an IntPtr I get from the 3rd party SDK    
//i also have width and height ints

bmp = new Bitmap(width, weight, PixelFormat.Format32bppRgb);          

BitmapData bData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);

int datasize = width * height * 4;
byte[] rgbValues = new byte[datasize];

Marshal.Copy(dataAdress, rgbValues, 0, datasize);
Marshal.Copy(rgbValues, 0, bData.Scan0, datasize);
bmp.UnlockBits(bData);

Then I call this function to convert the Bitmap to a BitmapSource:

BitmapSource source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bmp.Width, bmp.Height));

Note that I'm skipping some Disposing/cleanup for readability. I have to use BitmapSource so I can bind an ImageSource to display the images. If this were XNA, I would use Texture2Ds and this would fly. I figure since the underpinnings of WPF use DirectX there has got to be a better way than using gross Bitmaps.

Any ideas?

A: 

BitmapSource has static methods to create it from an array of bytes (see http://msdn.microsoft.com/en-us/library/ms616045%28v=VS.100%29.aspx). If for some reason this isn't good enough, Bitmap at least has a GetHBitmap function to retrieve the HBitmap instead of you creating it yourself via LockBits, etc (though the underlying implementation is probably similar).

JustABill