【问题标题】:.NET/C#/Xaml display video from bytes or Bitmap.NET/C#/Xaml 从字节或位图显示视频
【发布时间】:2025-08-05 23:45:01
【问题描述】:

我使用 IP 摄像头及其库从摄像头获取图像。

该库允许我获取字节数组或位图。我希望在我的 Xaml 窗口中显示视频。我需要一些快速的东西,但我不知道该怎么做。

目前我使用图像小部件并将位图转换为位图源:

            VideoWidget.Source = Imaging.CreateBitmapSourceFromHBitmap(camera.StreamUpdate().GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

它有效,但我认为如果我可以直接更新 bytes[],我可以做得更快。有没有办法做到这一点?

谢谢你:)

【问题讨论】:

  • 我猜你最终会实现库正在做的事情。你要写什么样的优化?

标签: c# xaml video bitmap bitmapsource


【解决方案1】:

您可以使用System.Windows.Media.Imaging.WriteableBitmap

要编写您的视频示例,请使用以下内容:

private void VideoSampleReady(byte[] sample, uint width, uint height, int stride, WriteableBitmap wBmp, System.Windows.Controls.Image dst)
{
    if (sample != null && sample.Length > 0)
    {
        this.Dispatcher.BeginInvoke(new Action(() =>
        {
            if (wBmp == null || wBmp.Width != width || wBmp.Height != height)
            {
                wBmp = new WriteableBitmap(
                    (int)width,
                    (int)height,
                    96,
                    96,
                    PixelFormats.Bgr24,
                    null);

                dst.Source = wBmp;
            }

            // Reserve the back buffer for updates.
            wBmp.Lock();

            Marshal.Copy(sample, 0, wBmp.BackBuffer, sample.Length);

            // Specify the area of the bitmap that changed.
            wBmp.AddDirtyRect(new Int32Rect(0, 0, (int)width, (int)height));

            // Release the back buffer and make it available for display.
            wBmp.Unlock();
        }), System.Windows.Threading.DispatcherPriority.Normal);
    }
}

【讨论】:

    最近更新 更多