C# Image.Clone Out of Memory Exception

前端 未结 6 675
礼貌的吻别
礼貌的吻别 2020-11-28 11:15

Why am I getting an out of memory exception?

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

splitBitmaps.Add(neededImage.Clone(rectDimensions, neededI

相关标签:
6条回答
  • 2020-11-28 11:25

    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.

    0 讨论(0)
  • 2020-11-28 11:31

    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 :-/

    0 讨论(0)
  • 2020-11-28 11:33

    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?

    0 讨论(0)
  • 2020-11-28 11:36

    I found that I was using Image.Clone to crop a bitmap and the width took the crop outside the bounds of the original image. This causes an Out of Memory error. Seems a bit strange but can beworth knowing.

    0 讨论(0)
  • 2020-11-28 11:37

    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.

    0 讨论(0)
  • 2020-11-28 11:44

    I struggled to figure this out recently - the answers above are correct. Key to solving this issue is to ensure the rectangle is actually within the boundaries of the image. See example of how I solved this.

    In a nutshell, checked to if the area that was being cloned was outside the area of the image.

    int totalWidth = rect.Left + rect.Width; //think -the same as Right property
    
    int allowableWidth = localImage.Width - rect.Left;
    int finalWidth = 0;
    
    if (totalWidth > allowableWidth){
       finalWidth = allowableWidth;
    } else {
       finalWidth = totalWidth;
    }
    
    rect.Width = finalWidth;
    
    int totalHeight = rect.Top + rect.Height; //think same as Bottom property
    int allowableHeight = localImage.Height - rect.Top;
    int finalHeight = 0;
    
    if (totalHeight > allowableHeight){
       finalHeight = allowableHeight;
    } else {
       finalHeight = totalHeight;
    }
    
    rect.Height = finalHeight;
    cropped = ((Bitmap)localImage).Clone(rect,    System.Drawing.Imaging.PixelFormat.DontCare);
    
    0 讨论(0)
提交回复
热议问题