C#新位图() - 内存不足

Tin*_*hip 5 c# dispose bitmap out-of-memory emgucv

我是DotNet编程的新手.我遇到了一个严重的问题,但我不知道为什么.我已经使用过Dispose()方法,但仍然会出现"Out of memory"问题.大约前30次,一切都很完美.然后,Out of memory发生了.此外,图像是13-16Mb.这是我的代码:

private void advanBtn_Click(object sender, EventArgs e)
{
    InvertFunction();
}

private void InverFunction()
{
    Bitmap bm = new Bitmap(imgBox.Image); // Out of memory
    Image<Gray, byte> EmguImage = new Image<Gray, byte>(bm);
    EmguImage = EmguImage.Not();
    imgBox.Image.Dispose();
    imgBox.Image = EmguImage.Bitmap;
    bm.Dispose();
    EmguImage.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

Har*_*rsh 3

尝试他们文档中的建议。

垃圾收集器决定处置图像的时间无法保证。当处理大图像时,建议调用 Dispose() 方法显式释放对象。或者,在C#中使用using关键字来限制图像的范围

    using (Bitmap bm = new Bitmap(imgBox.Image))
    {
        using (Image<Gray, Single> image = new Image<Gray, Single>(bm))
        {
            EmguImage = EmguImage.Not();
            imgBox.Image.Dispose();
            imgBox.Image = EmguImage.Bitmap;
        }
    }
Run Code Online (Sandbox Code Playgroud)

作为最后的手段,您可以尝试强制垃圾收集。但不建议这样做,只有在没有其他方法时才应使用。

  GC.Collect();
Run Code Online (Sandbox Code Playgroud)

我建议您在使用它之前先阅读它。