【问题标题】:C# WPF dispose of Image objectC# WPF 处理 Image 对象
【发布时间】:2013-06-30 04:47:59
【问题描述】:

我捕获屏幕,然后将图像数据保存到内存流中,以便将其设置为 BitmapImage 对象。

bmp = new System.Drawing.Bitmap((int)sel.rectSelectedArea.Width, (int)sel.rectSelectedArea.Height);
bounds = new System.Drawing.Rectangle((int)sel.rectSelectedArea.X, (int)sel.rectSelectedArea.Y, (int)sel.rectSelectedArea.Width, (int)sel.rectSelectedArea.Height);

using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
    g.CopyFromScreen(new System.Drawing.Point(bounds.Left, bounds.Top), System.Drawing.Point.Empty, bounds.Size);

ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;

frames.Add(new BitmapImage());
frames.Last().BeginInit();
frames.Last().StreamSource = ms;
frames.Last().EndInit();
frames.Last().Freeze();

然后当我需要向用户显示该框架时。我将选定的帧设置为 Image 对象的 Source。

imgExample.Source = frames[targetFrame];

问题是当我向用户显示另一个框架时。前一帧仍保留在内存中,因此在大约 200 帧后,它会累积 3-600,000 K 的内存,它永远不会释放。

有没有一种方法可以让 imgExample(图像对象)立即释放内存? 或者是否有一种方法可以覆盖相同的内存而不是为所有帧创建新对象。

【问题讨论】:

  • 我喜欢你将恐龙 System.Drawing 的东西带入 WPF 的方式。
  • 你可以试试 WriteableBitmap - 这些很容易随时更新。

标签: c# wpf image graphics gdi


【解决方案1】:
bmp.Dispose();
bmp = null;

GC.Collect();

【讨论】:

  • 我需要保留 BMP 以显示帧,但我需要它在不显示时并不总是在内存中。
  • 那么,您想保留 BMP... 但不在内存中?比如说,通过将其写入磁盘?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 2023-03-31
  • 2011-09-12
  • 2017-10-29
  • 1970-01-01
相关资源
最近更新 更多