AForge camera memory leak

天大地大妈咪最大 提交于 2019-12-02 01:07:34

AForge owns the bytes of the image, you should make your own deep copy. Passing the frame to the Bitmap constructor is not enough. If the framework is not able to properly dispose the bitmap because you have a reference to it, there's a leak.

Try with this:

private void NewFrame(object sender, NewFrameEventArgs args)
{
    Bitmap newFrame = AForge.Imaging.Image.Clone(args.Frame);
    PictureBox.FromBitmapImage(newFrame);
    newFrame.Dispose();
}

This works for me.

        if (pictureBox1.Image != null) {
            pictureBox1.Image.Dispose();
        }
        Bitmap bitmap = eventArgs.Frame.Clone() as Bitmap;
        pictureBox1.Image = bitmap;

Disposing picture box image right before assigning new one worked to prevent memory leak, but threw errors when I resized the picture box. Probably the problem is due to disposing the image too soon. What it worked for me was to keep old images in a queue, and dispose them with a delay of 5 images. This will give the picture box enough time to catch up.

private Queue<Image> _oldImages = new Queue<Image>();
...

if (pictureBox1.Image != null)
{
  _oldImages.Enqueue(pictureBox1.Image);
  if (_oldImages.Count > 5) 
  {
    var oldest = _oldImages.Dequeue();
    oldest.Dispose();
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!