gpt4 book ai didi

c# - WPF:如何高效地每秒更新图像 30 次

转载 作者:可可西里 更新时间:2023-11-01 08:06:04 25 4
gpt4 key购买 nike

我正在编写一个使用组件的 WPF 应用程序,该组件返回一个指向位图像素(步长 * 高度)的指针 (IntPtr)。我事先知道位图是一个24位的rgb,它的宽度和高度。

用这些位图更新图像控件构成了一个视频给用户,但我不确定最有效的方法是什么,大多数时候 CPU 使用率达到 75%+,内存从 40mb 变化到 500mb,我认为 GC 开始工作,然后再次下降到 40mm。该应用开始没有响应。

我该怎么办?

谢谢!

最佳答案

您很可能正在分配新的位图,这些位图不是一次性的。您应该分配一个 WriteableBitmap并更新它。链接的文档描述了锁定、更新和解锁 WriteableBitmap

背后的过程

在我使用 WPF 中的实时超声图像的软件上,我收到了一个 Windows 窗体位图,我使用 native CopyMemory 方法将其直接复制到 WriteableBitmap 中。即使进行这项更复杂的工作,CPU 也不会过度紧张,只要我能妥善处理,内存使用量就不会发生变化。希望这个例子可以帮助你:

// DLL returns images as a WinForms Bitmap
Bitmap bmp = myClass.getWinFormsBitmap();

// In my situation, the images are always 640 x 480.
BitmapData data = bmp.LockBits(new Rectangle(0, 0, 640, 480), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
this.writeableBitmap.Lock();

// Copy the bitmap's data directly to the on-screen buffers
NativeMethods.CopyMemory(this.writeableBitmap.BackBuffer, data.Scan0, ImageBufferSize);

// Moves the back buffer to the front.
this.writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, 640, 480));
this.writeableBitmap.Unlock();

bmp.UnlockBits(data);

// Free up the memory of the WinForms bitmap
bmp.Dispose();

其中 CopyMemory 定义为:

[DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory")]
public static extern void CopyMemory(IntPtr Destination, IntPtr Source, int Length);

关于c# - WPF:如何高效地每秒更新图像 30 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2455004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com