I'm creating an application (Windows Form) that allows the user to take a screenshot based on the locations they choose (drag to select area). I wanted to add a little "preview pane" thats zoomed in so the user can select the area they want more precisely (larger pixels). On a mousemove event i have a the following code...
private void falseDesktop_MouseMove(object sender, MouseEventArgs e)
{
zoomBox.Image = showZoomBox(e.Location);
zoomBox.Invalidate();
bmpCrop.Dispose();
}
private Image showZoomBox(Point curLocation)
{
Point start = new Point(curLocation.X - 50, curLocation.Y - 50);
Size size = new Size(100, 90);
Rectangle rect = new Rectangle(start, size);
Image selection = cropImage(falseDesktop.Image, rect);
return selection;
}
private static Bitmap bmpCrop;
private static Image cropImage(Image img, Rectangle cropArea)
{
if (cropArea.Width != 0 && cropArea.Height != 0)
{
Bitmap bmpImage = new Bitmap(img);
bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
bmpImage.Dispose();
return (Image)(bmpCrop);
}
return null;
}
The line that fails and has the Out of Memory exception is:
bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
Basically what this does is it takes a 100x90 rectangle around the mouse pointer and pulls that into the zoomBox, which is a picturebox control. However, in the process, i get an Out Of Memory error. What is it that i am doing incorrectly here?
Thanks for your assistance.
If the zoom box goes off the edge of the desktop area, then when you try to crop, you are asking the system to make a new image that includes pixels outside of the video memory area. Make sure to limit your zoom box so that none of its extents is less than 0 or greater than the screen edges.
Out of memory in C# imaging, is usually sign of wrong rect or point - a bit of red herring. I bet
start
has negative X or Y when error happens or the Size.Hight + Y or Size.Width + X is bigger than Hight or width of the image.If you are creating new bitmaps over and over, you might need to call
GC.Collect();
which will force C# to garbage collectyou should check if curLocation.X is larger than 50, otherwise your rectangle will start in the negative area (and of course curLocation.Y)
Use the Bitmap object like this:
MSDN explains that an
OutOfMemoryException
meanswhere
rect
is the first parameter to theBitmap.Clone
method.So check that the
cropArea
parameter is not larger than your image.In GDI+ an
OutOfMemoryException
does not really mean "out of memory"; the GDI+ error codeOufOfMemory
has been overloaded to mean different things. The reasons for this are historic and a well described by Hans Passant in another answer.