使用AForge和Graphics.FromImage.DrawImage防止OutOfMemoryException

时间:2015-01-03 19:30:27

标签: c# winforms out-of-memory webcam aforge

我编写了一个代码,允许用户从他们的网络摄像头开始和停止提要。我已经使用AForge.NET的NewFrameEventArgs每次更改时都用新帧更新PictureBox。一切都很完美但是每当我启动feed时,我的计算机上的RAM使用率会慢慢上升,直到发生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;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

在添加新的缩放图像之前,您需要处理上一个图像(只要它不为空)。

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。)