2

I have an array of images I have resized, what I'm trying to do is save them straight from the array...

foreach (Image I in Resizedimages)
            {
                string f = Environment.GetFolderPath(Environment.SpecialFolder.Desktop).ToString() + "\\NewImages\\" + names[n];

                I.Save(f, System.Drawing.Imaging.ImageFormat.Jpeg);
                n++;

            }

The problem is EVERY TIME I run the program I get an unhandled exception "A generic error occurred in GDI+" and I know for a fact that it is something to do with the save method. I'm assuming this question has been asked before, and if that is the case then I am sorry. I have tried many different fixes after searching for hours online I thought that maybe it's specific to my program. Any ideas?

aelsheikh
  • 2,268
  • 5
  • 26
  • 41

1 Answers1

0

The problem may be with something being locked, either by the Bitmap object or the Graphics object. Calling Dispose() on something might work or you can just copy to a new bitmap and save that:

       Bitmap copy = new Bitmap(I);
       copy.Save(f, System.Drawing.Imaging.ImageFormat.Jpeg);

To avoid file-locking by GDI, you can create an image from a MemoryStream:

       MemoryStream stream = new MemoryStream(File.ReadAllBytes(fileName));
       Image image = Image.FromStream(stream);
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • Making a copy of the Image hasn't stopped the error. The stream idea is getting an image from a path, that doesn't work since I've only got the image in an array, I just need to save it. – aelsheikh Apr 10 '11 at 00:47
  • Other things to try are disposing the Graphics object before saving and/or saving to a Stream instead of specifying a file name. – Mark Cidade Apr 10 '11 at 00:52
  • I've heard of the dispose solution but I that kept making the image null, so I assumed I was doing it wrong. Care to explain how I can go about doing this? – aelsheikh Apr 10 '11 at 01:00
  • Just dispose the Graphics object before you call Image.Save(). You can also try that with the copy-bitmap solution after disposing the original Image object as well. – Mark Cidade Apr 10 '11 at 02:49