简体   繁体   中英

Out Of Memory Exception - Bitmap.Clone

I'm working with a repo I found on Github, when I try to run it I get an exception in the following function:

public Color GetPixelColor(Point pos)
{
    Color pixelColor = new Color();
    Bitmap image = new Bitmap(1, 1);
    RECT rc;
    GetWindowRect(process, out rc);
    Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb);
    Graphics gfxBmp = Graphics.FromImage(bmp);
    IntPtr hdcBitmap = gfxBmp.GetHdc();
    PrintWindow(process, hdcBitmap, 0);
    gfxBmp.ReleaseHdc(hdcBitmap);
    gfxBmp.Dispose();
    image = bmp.Clone(new Rectangle(pos.X, pos.Y, 1, 1), PixelFormat.Format32bppArgb);
    pixelColor = image.GetPixel(0, 0);
    return pixelColor;
}

The problem line in particular is:

image = bmp.Clone(new Rectangle(pos.X, pos.Y, 1, 1), PixelFormat.Format32bppArgb);

Could the problem be that I have two displays? Any suggestions?

Edit: I've set the project to explicitly build for x64 and I have more than enough system memory.

Edit 2: Found the root of the problem.

There is a method called Unzoom()

while(!ColorDif.isCorrect(Home.bsProcess.image.GetPixelColor(new Point(3 + Settings.xDif,25 + Settings.yDif)), Color.FromArgb(0, 0, 0)))

Settings (what's being passed into the above code)

public static int xDif = 0, yDif = 0;

At runtime the exception is thrown when: xDif = -282 yDif = -45

Bitmap is a wrapper around the Win32 GDI methods. The error codes from those methods are sometimes translated somewhat confusingly into .NET exceptions. Thus, you probably don't have OOM, but rather some other GDI error.

GDI has a number of rules, which are not the case with WPF, and which could cause such an error. For example, the pixel dimensions of an element have to be at least 1x1. Also, any coordinates and sizes have to be valid. Probably your error has to do with an error there.

You should dispose the images you create. If you don't do so, you'll get the OutOfMemoryException.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM