Click here to Skip to main content
15,899,026 members
Please Sign up or sign in to vote.
3.67/5 (3 votes)
See more:
I have a small application that takes picture from my webcam. when i run it, it takes almost 1gb of the computer's memory. such a small application shouldn't take that much memory.

Please some once should help me on this.
below is my code

THis is the class that picture from the camera:

C#
using AForge.Imaging.Filters;
using AForge.Video;
using AForge.Video.DirectShow;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace PictureCapture
{
    public class ImageStore:IDisposable
    {
        public event EventHandler ImageChanged;
        public Image CurrentImage { get; private set; }
        public void StoreImage(Bitmap img)
        {
            //var imageCopy = img.Clone() as Image;
            if (CurrentImage != null) CurrentImage.Dispose();
            CurrentImage = img; //imageCopy;
            //imageCopy.Dispose();
            //img.Dispose();
            if (ImageChanged!=null)
            {
                var args = new EventArgs();
                ImageChanged(this, args);
            }
        }
        void Disposing(bool disposing)
        {
            if (disposing)
            {
                if (CurrentImage != null)
                {
                    ImageChanged -= (s, e)=> { };
                    CurrentImage.Dispose();
                    CurrentImage = null;
                }
            }
        }
        public void Dispose()
        {
            Disposing(true);
            GC.SuppressFinalize(this);
            //return;
        }
    }

    class ImageFromCamera
    {

        //private object timer;
        private FilterInfoCollection videoDevices;
        private VideoCaptureDevice videoSource = null;


        public ImageStore Store { get; private set; }
        public ImageFromCamera(ImageStore store)
        {
            Store = store;
        }
        string _cameraResolution;
        string _cameraInfo;
        //Image _cameraImage;
        public string CameraInfo
        {
            get { return _cameraInfo; }
        }
        public string CameraResolution
        {
            get { return _cameraResolution; }
        }
        //public Image CameraImage
        //{
        //    get { getCamList(); return _cameraImage; }
        //}


        private bool _started = false;
        public void Start()
        {
            if (_started) return;
            getCamList();
        }

        private void getCamList()
        {
            try
            {
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                //comboBox1.Items.Clear();
                if (videoDevices.Count == 0)
                {
                    _cameraResolution = "Нет устройства захвата в системе";
                    //throw new ApplicationException();
                }
                else
                {
                    videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
                    try
                    {
                        //Check if the video device provides a list of supported resolutions
                        if (videoSource.VideoCapabilities.Length > 0)
                        {
                            string highestSolution = "0;0";
                            //Search for the highest resolution
                            for (int i = 0; i < videoSource.VideoCapabilities.Length; i++)
                            {
                                if (videoSource.VideoCapabilities[i].FrameSize.Width > Convert.ToInt32(highestSolution.Split(';')[0]))
                                    highestSolution = videoSource.VideoCapabilities[i].FrameSize.Width.ToString() + ";" + i.ToString();
                                
                            }
                            int highResolutionCount = Convert.ToInt32(highestSolution.Split(';')[1]);
                            //Set the highest resolution as active
                            videoSource.VideoResolution = videoSource.VideoCapabilities[highResolutionCount];
                            //videoSource.VideoResolution = videoSource.VideoCapabilities[5];
                            _cameraResolution = "Camera Resolution:" + videoSource.VideoCapabilities[highResolutionCount].FrameSize.Width.ToString() + "x"+ videoSource.VideoCapabilities[highResolutionCount].FrameSize.Height.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new ApplicationException("Something went wrong. See inner exception for details", ex);
                    }

                    videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
                    Stop();
                    videoSource.Start();
                    //Timer timer = new Timer(1000);
                    //timer.Elapsed += async (sender, e) => await HandleTimer();
                    //timer.Start();

                    _cameraInfo = "устройство работает... " + videoSource.FramesReceived.ToString() + " FPS";
                }
            }
            catch (ApplicationException)
            {
                //DeviceExist = false;
                _cameraResolution = "Нет устройства захвата в системе";
                //comboBox1.Items.Add("No capture device on your system");
            }
        }

        public void Stop()
        {
            if (!(videoSource == null))
                if (videoSource.IsRunning)
                {
                    videoSource.SignalToStop();
                    videoSource = null;
                }
            //throw new NotImplementedException();
        }

        private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap img = (Bitmap)eventArgs.Frame.Clone();
           // using (Bitmap img = (Bitmap)eventArgs.Frame.Clone())
           // {               
            var filll = new Mirror(false, true);
                filll.ApplyInPlace(img);
                Store.StoreImage(img);                 
           // }

            
        }

    }
}


This is my code to take the picture into the picture boxes


C#
public partial class Form1 : Form
   {

       string _fileName;
       ImageStore _store = new ImageStore();
       string _cameraResolution;

       public Form1(ImageStore store, string filemane, string cameraResolution)
       {
          InitializeComponent();
           _fileName = filemane;
          _store = store;

           _cameraResolution = cameraResolution;
           label2.Text = cameraResolution;
           _store.ImageChanged += (s, e) =>
           {
               using (Image _image = (s as ImageStore).CurrentImage)
               {

               Bitmap _cropImage = (Bitmap)_image.Clone();
               Bitmap _cropImage2 = (Bitmap)_image.Clone();
               //Bitmap _getcroppedImage;
              Crop filter = new Crop(new Rectangle(Convert.ToInt32(_cropImage.Width / 2.9), _cropImage.Height / 10, (Convert.ToInt32(_cropImage.Width / 3)), (Convert.ToInt32(_cropImage.Height / 1.2))));
              Bitmap _getcroppedImage = filter.Apply(_cropImage);
                   //Crop filt = new Crop(new Rectangle(120, 80, 380, 320));
              pictureBox1.Image = GetShapesForImage(_cropImage2);
              pictureBox2.Image = _getcroppedImage;
             }

           };
           //_store.ImageChanged -= (s, e) => { };

       }


C#
private Image GetShapesForImage(Bitmap _img)
        {
           // Bitmap _img = (Bitmap)ImageFile.Clone();
            using (Graphics g1 = Graphics.FromImage(_img))
            {

                Pen pen1 = new Pen(Color.FromArgb(160, 255, 160), 2);
                Pen pen2 = new Pen(Color.Red, 2);

                Pen blackPen = new Pen(Color.White, 3);
                blackPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
                // Create rectangle for ellipse.
                
                Rectangle rect = new Rectangle(Convert.ToInt32(_img.Width / 3), _img.Height / 10, (Convert.ToInt32(_img.Width / 3)), (Convert.ToInt32(_img.Height / 1.3)));
                g1.DrawEllipse(blackPen, rect);
                g1.DrawLine(blackPen, _img.Width / 2, 0, _img.Width / 2, _img.Width);
                // Draw ellipse to screen.
                

                g1.DrawLine(blackPen, _img.Width/3.000f, _img.Height/2.000f, _img.Width/1.500f, _img.Height/2.000f);

                //g1.Dispose();
                //pictureBox1.Image = _img;
                return _img;
            }
        }


What I have tried:

I've tried using() and IDisposable class but it didn't solve the problem.
Posted
Comments
[no name] 27-Jun-16 7:34am    
Probably memory leak in AForge, read this : http://stackoverflow.com/questions/15899970/aforge-camera-memory-leak
Member 8354645 27-Jun-16 9:05am    
I added this line of code but it still the same

if (pictureBox1.Image != null)
{
pictureBox2.Image.Dispose();
pictureBox1.Image.Dispose();
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900