VB.Net Error: A generic error occurred in GDI+

If you’ve ever encountered the “A generic error occurred in GDI+” error, it may have resulted in the pulling of hair, throwing of blunt objects or the creation of new swear words!

I recently faced this problem in a small app I did, and after hours of scouring Google, I couldn’t find a definitive answer…

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
   at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
   at System.Drawing.Image.Save(String filename, ImageFormat format)
   at System.Drawing.Image.Save(String filename)

For reference, here is the code I was using:

Private Sub CreateScreenshot()
     Dim img As New Bitmap(Me.Width, Me.Height)
     Dim gr As Graphics = Graphics.FromImage(img)   
     gr.CopyFromScreen(New Point(Me.Left, Me.Top), New Point(0, 0), img.Size)
     Dim newimg As Bitmap
     img.Save(Environment.SpecialFolder.MyDocuments & "\alarm.png", ImageFormat.Png)
End Sub

Can you spot the mistake?

Now, most online “fixes” tell you it’s a permissions issue or a “locked” file issue. I knew it wasn’t a permissions issue, as it’s “My Documents” (it has the word “My” in the folder for cryin’ out loud!), and I knew it wasn’t a “locked” issue because I wasn’t reading in an Image file.

So, after some time on the throne (this is where most of my solutions are devised), I thought, “maybe I need to verify the path I’m trying to save to actually exists.”

I don’t use the Environment.SpecialFolder shortcuts very often, so I’ll chalk it up to that, but with a bit of debugging (read: a Messagebox echoing my .Save path), I found out that I need to enclose the Environment.SpecialFolder.MyDocuments call in another Method that actually returns the desired path. This method is System.Environment.GetFolderPath.

After changing my .Save line to:

img.Save(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\alarm.png", ImageFormat.Png)

it all worked without error!

So… if you’re struggling with this error and you’ve verified it’s not a permissions issue or the “file being in use” issue, you might just double-check to make sure you’re saving to a “real” filepath!

Comments welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *