Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# New bitmap() - Out of memory

I'm newbie at DotNet programming. I got a serious problem for me but I don't know why. I already used Dispose() method but "Out of memory" problem still occurs. At about first 30 times, everything works perfectly. Then, Out of memory happens. Furthermore, the images is from 13-16Mb. This is my code:

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();
}
like image 755
Tin Chip Avatar asked Aug 18 '17 09:08

Tin Chip


2 Answers

Try the suggestion in their documentation.

The time of when garbage collector decides to dispose the image is not guaranteed. When working with large image, it is recommend to call the Dispose() method to explicitly release the object. Alternatively, use the using keyword in C# to limit the scope of the image

    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;
        }
    }

As a last resort you can try forcing garbage collection. BUT this is not recomended and should be used only if you have no other way.

  GC.Collect();

I would suggest you to read about it before using it here.

like image 80
Harsh Avatar answered Oct 16 '22 08:10

Harsh


It might not be applicable anymore, but there were some version of the CLR that definitely had bugs with the LOH, where images normally get allocated. Might want to check that topic. A workaround was to manually check, if there was enough coherent memory (for external memory allocation) before allocating, which is a bit of a pain to do in C#. Just suggesting that you might not do something wrong.

I also had the problems with using OpenCV/Emgu and used opencvsharp for some problems. It is a more direct wrapper where you have to be very careful about memory allocation. It has been some time though and I cannot really remember the exaxt problem. It had to do with memory allocation. It should also be fixed by now I think.

Ended up having both as a dependency and it doesn't help for having clean code.

Otherwise, try to use the using statement other answers are suggesting. It calls .Dispose() automatically and starting the GC right away. That way, your memory doesn't fragment as much. You can also write..

using(Image a, Image b, Image c, ...) {}

... as long as the object implement IDisposable

like image 23
Donald J. Trump Avatar answered Oct 16 '22 09:10

Donald J. Trump