I have this method that is supposed to take a screenshot and return the image to the calling method.
public static Bitmap TakeScreenshot(int x, int y, int height, int width)
{
Rectangle bounds = new Rectangle(0, 0, height, width);
Bitmap bitmap;
using (bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(x, y), Point.Empty, bounds.Size);
}
}
return bitmap;
}
The problem is that when I try to save the picture:
Bitmap bitmap = MyClass.TakeScreenshot(0, 0, 200, 200);
bitmap.Save(@"C:\test.jpg", ImageFormat.Jpeg);
Then I get an error at the save-method.
ArgumentException was unhandled.
Parameter is not valid.
It works fine if I try to save it inside the method like this:
public static Bitmap TakeScreenshot(int x, int y, int height, int width)
{
Rectangle bounds = new Rectangle(0, 0, height, width);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(x, y), Point.Empty, bounds.Size);
}
bitmap.Save(@"c:\begin.tiff", ImageFormat.Tiff);
}
}
What am I missing here?
In your first example, the
Bitmaphas been disposed via theusingstatement, you are then saving afterwards.In the second example, you are saving before the disposal.
All you should need to do is not wrap the bitmap in a
usingstatement, Instead, either leave it for the garbage collector, or call.Dispose()after you’ve saved it.Personally, for items that implement the
IDisposableinterface, I tend to make sureDisposeis called, unless my usage dictates keeping it alive.