piotrMaPytanie
piotrMaPytanie

Reputation: 11

Convert Bitmap to BitmapSource

I have problem with converting bitmap to bitmapsource, I write something like this http://www.codeproject.com/KB/WPF/BitmapToBitmapSource.aspx?msg=3590727 , but I get exceptions: A first chance exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll :/ I must convert bitmap to bitmapsource, beacouse I use aforge.net to caputer image from webcam. Do you know why I get this exception ? ( everything works good with winforms ) Or mayby you know library looking similarity to aforge which I can use with WPF?

My code:

private void NewFrameHandler(Bitmap bitmap)
{
    BitmapSource bitSrc = null;
    var hBitmap = bitmap.GetHbitmap();

     bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
         hBitmap,
         IntPtr.Zero, Int32Rect.Empty,
            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

    image1.Source = bitSrc;
}

Upvotes: 1

Views: 2466

Answers (1)

bigfoot
bigfoot

Reputation: 455

The code looks good to me, though you need to use the PInvoke method DeleteObject to release the memory used by hbitmap.

The only reason I can think of it failing, is that there is something wrong with the bitmap being converted.

Upvotes: 0

Related Questions