-1

I know this question has been answered before. But none of the answers are correct. How can I capture the image of a windows form and save it. I use this:

Bitmap bmp = new Bitmap(this.Width, this.Height);
this.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
bmp.Save(@"C://Desktop//sample.png",ImageFormat.Png);

but get the error:

A generic error occurred in GDI+

I have also read about this error but none of the suggestions work for me! Please help

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Mike
  • 369
  • 5
  • 21

2 Answers2

7

The problem is in bmp.Save(@"C://Desktop//sample.png",ImageFormat.Png);.

First it must be @"C:\Desktop\sample.png", you don't need to escape anything with verbatim string.

Second make sure the path is correct and you have permission to write to.

Third as Sayse point out dispose the bitmap.

using(Bitmap bmp = new Bitmap(this.Width, this.Height))
{
    this.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
    bmp.Save(@"C:\Desktop\sample.png",ImageFormat.Png); // make sure path exists!
}
Scott
  • 4,458
  • 1
  • 19
  • 27
Alessandro D'Andria
  • 8,663
  • 2
  • 36
  • 32
  • editting: it worked fine. Thank you. Please ignore the following thank you. Actually that was my problem in the first place. How do I dispose the bitmap? by using bmp.Dispose? when I use this before the saving I get error. when I use it after saving I get the same GDI+ error – Mike Oct 22 '14 at 08:00
  • If anyone needs without border: https://stackoverflow.com/a/23187599/13701662 – SBU Feb 06 '22 at 02:07
0

Your path is in wrong format. Should be:

bmp.Save("C:\\Desktop\\sample.png",ImageFormat.Png);

What is more - check if the folder exists

SOReader
  • 5,697
  • 5
  • 31
  • 53