[英]How do I prevent a bitmap variable taking up too much memory when initializing it in a loop?
I'm making a screen recording program so how it works is that it take a lot of pictures then stores them to make it into a video, but i ran into a problem when making the program run longer than 8 seconds. 我正在制作一个屏幕录制程序,所以它的工作方式是先拍摄大量图片,然后将它们存储为视频,但是当程序运行超过8秒时,我遇到了一个问题。 It uses way more memory than it should. 它使用的内存多于应有的数量。
while (DateTime.Now.Minute * 60000 + DateTime.Now.Second * 1000 + DateTime.Now.Millisecond < startTime+20000) {
memoryImage = new Bitmap(ScreenBounds.Width, ScreenBounds.Height);
// Create graphics
Console.WriteLine("Creating Graphics...");
Console.WriteLine();
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
// Copy data from screen
Console.WriteLine("Copying data from screen...");
Console.WriteLine();
try
{
memoryGraphics.CopyFromScreen(0, 0, 0, 0, ScreenBounds);
}
catch (Exception er)
{
Console.WriteLine("Error when copying data from screen error: " + er.Message + " : breaking script");
break;
}
// Save it!
Console.WriteLine("Saving the image...");
images.Add(memoryImage);
GC.Collect();
GC.WaitForFullGCComplete();
As you can see I tried forcing garbage collection; 如您所见,我尝试过强制垃圾回收。 the problem variable is memoryImage or at least that's what it seems to be I'm not completely sure. 问题变量是memoryImage,或者至少那是我不确定的样子。 How can I get this program to use less memory, so it doesn't crash? 我如何才能使该程序使用更少的内存,从而不会崩溃?
UPDATE: I added memoryImage.Dispose(); 更新:我添加了memoryImage.Dispose(); to the end of the first part which fixed the memory issue but now I get the error: 至第一部分的末尾,该部分解决了内存问题,但是现在出现错误:
An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll System.Drawing.dll中发生类型为'System.ArgumentException'的未处理异常
Additional information: Parameter is not valid. 附加信息:参数无效。
in this block of code: 在这段代码中:
VideoWriter video = new VideoWriter(@"outputVideo.avi", (int)AvgFPSList.Average(), Screen.PrimaryScreen.Bounds.Size, true);
for (int x = 0; x < images.Count; x++)
{
Image<Emgu.CV.Structure.Bgr, Byte> img = new Image<Emgu.CV.Structure.Bgr, Byte>(images[x]); << error here
video.Write(img.Mat);
}
To answer the original question for future viewers, 为了回答未来观众的原始问题,
The Graphics class implements IDisposable. Graphics类实现IDisposable。 To remove it from memory either wrap it in a using statement or manually call Dispose on it when you are finished using it. 要从内存中删除它,可以将其包装在using语句中,或者在使用完毕后手动对其调用Dispose。
Using example: 使用示例:
using (Graphics memoryGraphics = Graphics.FromImage(memoryImage))
{
// perform operations on memoryGraphics
}
Bitmap also implements IDisposable and should be properly disposed of at some point. 位图还实现IDisposable,应在某个时候适当处理。
The authors update of the question may be a different problem. 作者对该问题的更新可能是一个不同的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.