1
public void EditAndSave(String fileName) {
    Bitmap b = new Bitmap(fileName);
    /**
    * Edit bitmap b... draw stuff on it...
    **/
    b.Save(fileName); //<---------Error right here
    b.Dispose();
}

My code is similar to the above code. When i try to save the file i just opened, it won't work. When i try saving it with a different path, it works fine. Could it be that the file is already open in my program so it cannot be written to? I'm very confused.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Mohammad Adib
  • 788
  • 6
  • 19
  • 39

3 Answers3

2

You are correct in that it is locked by your program and therefore you can't write to it. It's explained on the msdn-page for the Bitmap class (http://msdn.microsoft.com/en-us/library/3135s427.aspx).

One way around this (from the top of my head, might be easier ways though) would be to cache image in a memorystream first and load it from there thus being able to close the file lock.

    static void Main(string[] args)
    {
        MemoryStream ms = new MemoryStream();
        using(FileStream fs = new FileStream(@"I:\tmp.jpg", FileMode.Open))
        {
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            ms.Write(buffer, 0, buffer.Length);
        }

        Bitmap bitmap = new Bitmap(ms);

        // do stuff

        bitmap.Save(@"I:\tmp.jpg");
    }
Karl-Johan Sjögren
  • 16,544
  • 7
  • 59
  • 68
0

I've not been in exactly the same situation as you, but I have had problems with open image files being kept open.

One suggestion is that you load the image into memory using the BitmapCacheOption.OnLoad, see my answer to this post: Locked resources (image files) management.

Then, after editing, that image can be saved to the the same file using a FileStream, that is described for example here: Save BitmapImage to File.

I'm not sure it is the easiest or most elegant way, but I guess it should work for you.

Community
  • 1
  • 1
ekholm
  • 2,543
  • 18
  • 18
0

Indeed there may be many reasons for seeing this exception.

Note that if you're using PixelFormat.Format16bppGrayScale, it's not supported in GDI+ and fails in the way shown. It seems the only workaround for using proper 16-bit gray scale is to use the newer System.Windows.Media namespace from WPF.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742