我已经写了一个代码,允许用户从他们的网络摄像头启动和停止一个提要。我使用了AForge.NET的NewFrameEventArgs在每次更改新框架时使用新框架更新PictureBox。但是,无论何时启动提要,我的计算机上的内存使用量都会缓慢上升,直到出现OutOfMemoryException。
你能帮我弄清楚怎么清理或冲洗这个吗?当我得到异常时,它发生在ScaleImage代码的底部:
System.Drawing.Graphics.FromImage(newScaledImage).DrawImage(image, 0, 0, newWidth, newHeight);到目前为止我的代码是:
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using AForge.Video;
using AForge.Video.DirectShow;
namespace WebCameraCapture
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private VideoCaptureDevice FinalFrame;
System.Drawing.Bitmap fullResClone;
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
pictureBox1.Image = ScaleImage((Bitmap)eventArgs.Frame.Clone(), 640, 480);
}
private void btn_startCapture_Click(object sender, EventArgs e)
{
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);//Specified web cam and its filter moniker string.
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice) { comboBox1.Items.Add(Device.Name); }
comboBox1.SelectedIndex = 0; //Default index.
FinalFrame = new VideoCaptureDevice();
}
//This ScaleImage is where the OutOfMemoryException occurs.
public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxWidth, int maxHeight) //Changes the height and width of the image to make sure it fits the PictureBox.
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newScaledImage = new Bitmap(newWidth, newHeight);
System.Drawing.Graphics.FromImage(newScaledImage).DrawImage(image, 0, 0, newWidth, newHeight); // <<<< RIGHT HERE
return newScaledImage;
}
}
}发布于 2015-01-05 10:09:05
在添加新的缩放映像之前,您需要释放前一个映像(只要它不是空的)。
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); }
Bitmap tempBitmap = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = ScaleImage(tempBitmap, 640, 480);
tempBitmap.Dispose();
}问:是否真的有必要创建输入映像的克隆?eventArgs.Frame究竟引用了什么?(我没有AForge。)
https://stackoverflow.com/questions/27758731
复制相似问题