Search code examples
c#gdi+image-manipulation

Saving a modified image to the original file using GDI+


I was loading a Bitmap Image from a File. When I tried to save the Image to another file I got the following error "A generic error occurred in GDI+". I believe this is because the file is locked by the image object.

Ok so tried calling the Image.Clone function. This still locks the file.

hmm. Next I try loading a Bitmap Image from a FileStream and load the image into memory so GDI+ doesn't lock the file. This works great except I need to generate thumbnails using Image.GetThumbnailImage method it throws an out of memory exception. Apparently I need to keep the stream open to stop this exception but if I keep the stream open then the file remains locked.

So no good with that method. In the end I created a copy of the file. So now I have 2 versions of the file. 1 I can lock and manipulate in my c# program. This other original file remains unlocked to which I can save modifications to. This has the bonus of allowing me to revert changes even after saving them because I'm manipulating the copy of the file which cant change.

Surely there is a better way of achieving this without having to have 2 versions of the image file. Any ideas?


Solution

  • I have since found an alternative method to clone the image without locking the file. Bob Powell has it all plus more GDI resources.

          //open the file
          Image i = Image.FromFile(path);
    
          //create temporary
          Image t=new Bitmap(i.Width,i.Height);
    
          //get graphics
          Graphics g=Graphics.FromImage(t);
    
          //copy original
          g.DrawImage(i,0,0);
    
          //close original
          i.Dispose();
    
          //Can now save
          t.Save(path)