C#WPF处理Image对象

时间:2013-07-02 17:29:23

标签: c# wpf image graphics gdi

我捕获屏幕,然后将图像数据保存到内存流中,以便将其设置为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(Image对象)立即释放内存? 或者是否有一种覆盖相同内存的方法,而不是为所有帧创建新对象。

1 个答案:

答案 0 :(得分:0)

bmp.Dispose();
bmp = null;

GC.Collect();