2

I need to convert webcam-picture (retrieved by AForge) to a BitmapImage in order to use it as a source for the WPF Image-control.

The following source is working but it runs with only like 5-7 FPS on a 3rd Gen i7.

Are there better alternatives to improve the speed?

    void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
    {

        System.Drawing.Image img = eventArgs.Frame;
        BitmapImage bitmapImage;

        using (MemoryStream memory = new MemoryStream())
        {

            img.Save(memory, ImageFormat.Bmp);
            bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            memory.Seek(0, SeekOrigin.Begin);
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
        }

        bitmapImage.Freeze();
        Dispatcher.BeginInvoke(new ThreadStart(delegate
        {
            outputImage.Source = bitmapImage;
        }));
    }
Hedge
  • 16,142
  • 42
  • 141
  • 246
  • You may try [CreateBitmapSourceFromHBitmap](http://stackoverflow.com/q/1546091/1136211). – Clemens Feb 10 '15 at 12:03
  • There is no method `GetHBitmap()` for `System.Drawing.Image` – Hedge Feb 10 '15 at 12:22
  • 1
    It certainly is a `System.Drawing.Bitmap`. Did you try to cast it? – Clemens Feb 10 '15 at 12:23
  • Just checked it. `NewFrameEventArgs.Frame` is actually already declared as Bitmap. So change your variable declaration to `var img = eventArgs.Frame;`. – Clemens Feb 10 '15 at 12:25
  • 1
    Anyway, the fastest way might be to (re-)use a single WriteableBitmap, like shown in [this answer](http://stackoverflow.com/a/9329047/1136211). – Clemens Feb 10 '15 at 12:30
  • The solutin with the HBitmap gives me this exception `A first chance exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll`` – Hedge Feb 10 '15 at 12:39
  • You should [Freeze](https://msdn.microsoft.com/en-us/library/ms557735.aspx) the BitmapSource before passing it the the BeginInvoke delegate. Or you move the whole conversion code to the BeginInvoke delegate. Hard to tell without seeing your code, or even a stack trace of the exception. – Clemens Feb 10 '15 at 12:43

0 Answers0