Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a Bitmap type?

Tags:

c#

bitmap

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?

like image 489
Kasper Hansen Avatar asked Jun 12 '26 05:06

Kasper Hansen


1 Answers

In your first example, the Bitmap has been disposed via the using statement, 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 using statement, Instead, either leave it for the garbage collector, or call .Dispose() after you've saved it.

Personally, for items that implement the IDisposable interface, I tend to make sure Dispose is called, unless my usage dictates keeping it alive.

like image 175
Adam Houldsworth Avatar answered Jun 13 '26 19:06

Adam Houldsworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!