views:

4333

answers:

4

Why am I getting an out of memory exception?

So this dies in C# on the first time through:

splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat));

Where splitBitmaps is a List<BitMap> BUT this works in VB for at least 4 iterations:

arlSplitBitmaps.Add(Image.Clone(rectDimensions, Image.PixelFormat))

Where arlSplitBitmaps is a simple array list. (And yes I've tried arraylist in c#)

This is the fullsection:

for (Int32 splitIndex = 0; splitIndex <= numberOfResultingImages - 1; splitIndex++)
{ 
  Rectangle rectDimensions;

  if (splitIndex < numberOfResultingImages - 1) 
  {
    rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0, 
      splitImageWidth, splitImageHeight); 
  } 
  else 
  {
    rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0, 
     sourceImageWidth - (splitImageWidth * splitIndex), splitImageHeight); 
  } 

  splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat));

}

neededImage is a Bitmap by the way.

I can't find any useful answers on the intarweb, especially not why it works just fine in VB.

Update:

I actually found a reason (sort of) for this working but forgot to post it. It has to do with converting the image to a bitmap instead of just trying to clone the raw image if I remember.

+1  A: 

Make sure that you're calling .Dispose() properly on your images, otherwise unmanaged resources won't be freed up. I wonder how many images are you actually creating here -- hundreds? Thousands?

Dave Markle
Doubt it's memory, blows up first time through.
Programmin Tool
Yeah bitmap .Dispose doesn't affect these OoM exceptions, in my experience.
Jared Updike
A: 

This is a reach, but I've often found that if pulling images directly from disk that it's better to copy them to a new bitmap and dispose of the disk-bound image. I've seen great improvement in memory consumption when doing so.

Dave M. is on the money too... make sure to dispose when finished.

Mike L
+7  A: 

Clone() may also throw an Out of memory exception when the coordinates specified in the Rectangle are outside the bounds of the bitmap. It will not clip them automatically for you.

TomA
A: 

I got this too when I tried to use the Clone() method to change the pixel format of a bitmap. If memory serves, I was trying to convert a 24 bpp bitmap to an 8 bit indexed format, naively hoping that the Bitmap class would magically handle the palette creation and so on. Obviously not :-/

Andy