0

I need to draw a video to another window where I could get the device context hDC using GetDCEx. I can already achieve drawing using System.Drawing.Graphics:

g = Graphics.FromHdc(hdc);
// Now I need to get the video frame/bitmap here
g.DrawImage(frameBitmap, 0, 0);

However I don't think System.Drawing has any class for video rendering, so I plan to use System.Windows.Media.MediaPlayer. However, the best I could do is to get it to RenderTargetBitmap. There is a way to use an encoder to render to Bitmap file and then decoding it to System.Drawing.Image, but I think it would be too slow.

So either of these can solve my problem, please tell me if any is possible:

  • Can a WPF DrawingVisual draw on a hDC?

  • Can a DrawingVisual somehow draws on a Graphics?

  • A quick way to get System.Drawing.Bitmap from DrawingVisual/MediaPlayer/VideoDrawing?

Luke Vo
  • 17,859
  • 21
  • 105
  • 181

1 Answers1

0

I am using Bitmap data copying (LockBits) and it's fast enough. Thanks to this answer.

    public Bitmap Render()
    {
        var bitmapRender = this.CreateRenderTargetBitmap();

        using (var drawingContext = this.drawingVisual.RenderOpen())
        {
            drawingContext.DrawVideo(this.MediaPlayer, this.drawingRect);
            drawingContext.Close();
        }   

        bitmapRender.Render(this.drawingVisual);

        var result = new Bitmap(this.Width, this.Height, DrawingPixelFormat);
        var bitmapData = result.LockBits(
            this.renderRect, 
            System.Drawing.Imaging.ImageLockMode.WriteOnly, 
            DrawingPixelFormat);

        bitmapRender.CopyPixels(
            Int32Rect.Empty,
            bitmapData.Scan0,
            bitmapData.Stride * bitmapData.Height,
            bitmapData.Stride);

        result.UnlockBits(bitmapData);

        return result;
    }

    RenderTargetBitmap CreateRenderTargetBitmap() => new RenderTargetBitmap(
            this.Width, this.Height,
            this.Dpi, this.Dpi,
            WpfPixelFormat);
Luke Vo
  • 17,859
  • 21
  • 105
  • 181