Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get the an out of memory error when I use using?

I have the following method, to convert a BitmapImage to a System.Drawing.Bitmap:

public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
    Bitmap bitmap;

    using (var ms = new MemoryStream())
    {
        var encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
        encoder.Save(ms);

        bitmap = new Bitmap(ms);
    }

    return bitmap;
}

Whenever I try and use the returned Bitmap object, I get the following error:

OutOfMemoryException occured - Out of memory.

However, whenever I replace the code with this:

public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
    var ms = new MemoryStream();

    var encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bitmapImage));

    encoder.Save(ms);

    return new Bitmap(ms);
}

This works fine. However, I am pretty sure that I am supposed to use using as the MemoryStream object implements IDisposable. What's going on here?

like image 726
JMK Avatar asked Jan 21 '13 13:01

JMK


People also ask

Why do I keep getting out of memory error?

An out of memory error causes programs — or even the entire computer — to power down. This problem is typically caused either by low random access memory (RAM), too many programs or hardware pieces running at once, or a large cache size that absorbs a large amount of memory.

How do I avoid out of memory exception?

Well, according to the topic of the question, best way to avoid out of memory exception would be not to create objects that fill in that memory. Then you can calculate the length of your queue based on estimate of one object memory capacity. Another way would be to check for memory size in each worker thread.


1 Answers

Bitmap's constructor Bitmap Constructor (Stream) claims that

You must keep the stream open for the lifetime of the Bitmap.

In your case, when you're using using statement, stream (being Disposable) automatically disposed, so your Bitmap object becomes invalid. It's not about that you allocate too much memory, but about that bitmap point to -something that no longer exists.

like image 92
Tigran Avatar answered Nov 15 '22 21:11

Tigran