I have this JPEG image, that opens fine in Picasa, Photoshop, web browser, etc., but in .NET it just refuses to work.
Image image = Image.FromFile(@"myimage.jpg");
image.Save(@"myimage2.jpg");
// ExternalException - A generic error occurred in GDI+.
Is there a way to recover it in .NET so I can work with it (I need to resize it), without fixing the problem at the source?
Full exception details:
source: System.Drawing type: System.Runtime.InteropServices.ExternalException message: A generic error occurred in GDI+. stack trace: 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) at ConsoleApplication20.Program.Main(String[] args) in C:\Users\sam\Desktop\S ource\ConsoleApplication20\ConsoleApplication20\Program.cs:line 16
This issue is reproducible on Windows 7.
It seems to work fine on Windows XP and Vista, but not Windows 7.
I was able to find this issue on Microsoft Connect. It’s not identical to your issue but it looks very similar – an
ExternalExceptionoccurring when trying to resave a JPEG file. Currently at 16 repros including some comments that the issue still exists in the final release.So it looks not to be a bug in the .NET Framework, but a bug in Windows 7 – specifically, a bug in the
GdipSaveImageToStreamAPI.The workaround, as others have mentioned, is to force a conversion to another format. That’s what both Marc and Darin’s answers are doing. There is obviously some “extra” information in the JPEG file that is triggering the bug in Win7. When you convert to a different format or make a bitmap copy, that information (EXIF maybe?) is eliminated.