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.

4
  • Do you get an exception? How does it "not work"? Commented Jun 26, 2012 at 7:38
  • I'm sure it's not a generic error, but rather one containing a potentially useful description - but you've not given us that information. Commented Jun 26, 2012 at 7:38
  • All it says is "A generic error occured in GDI+" Commented Jun 26, 2012 at 7:48
  • 2
    I believe the .NET wrapper around GDI+ is pretty sparse on error details. Commented Jun 26, 2012 at 8:06

3 Answers 3

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");
    }
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.